Procházet zdrojové kódy

决策支持优化

zck před 2 týdny
rodič
revize
e8fa25d397

+ 378 - 46
application/api/controller/Achievementatestatistics.php

@@ -717,46 +717,61 @@ class  Achievementatestatistics extends Api
 //        $this->success('成功', $data);
 //    }
     public function left_Productyear() {
-        $list = \db('产品_基本资料')
-            ->field('客户编号,客户名称')
-            ->group('客户编号,客户名称')
-            ->where('客户编号','<>','')
-            ->order('客户编号')
+        // 先从工单_质量考核汇总获取产品代号及各产品最新账期(sys_ny 格式 YYYYMM,如 202610)
+        $list = \db('工单_质量考核汇总')
+            ->field('产品代号, MAX(sys_ny) as latest_ny')
+            ->where('产品代号', '<>', '')
+            ->group('产品代号')
             ->select();
 
-        $data['翌星工单'] = [];
-        $data['MN工单'] = [];
-        $seenEntries = []; // 添加这个变量来跟踪已处理的条目
+        // 根据产品代号到产品_基本资料获取客户编号和客户名称
+        $codes = array_unique(array_map(function ($item) {
+            return trim($item['产品代号']);
+        }, $list));
+        $productRows = \db('产品_基本资料')
+            ->field('产品编号, 客户编号, 客户名称')
+            ->whereIn('产品编号', $codes)
+            ->select();
+        $productMap = [];
+        foreach ($productRows as $p) {
+            $productMap[trim($p['产品编号'])] = [
+                '客户编号' => trim($p['客户编号']),
+                '客户名称' => trim($p['客户名称'])
+            ];
+        }
 
-        foreach ($list as $key => $value) {
-            $value['客户编号'] = rtrim($value['客户编号']);
-            $value['客户名称'] = rtrim($value['客户名称']);
-            if (empty($value['客户名称'])) {
+        // 按客户汇总,取该客户下所有产品的最新账期年份
+        $customerYear = [];
+        foreach ($list as $value) {
+            $code = trim($value['产品代号']);
+            if (!isset($productMap[$code])) {
                 continue;
             }
-
-            // 获取工单信息,包含Sys_rq字段
-            $productIng = \db('工单_基本资料')
-                ->field('Sys_rq')
-                ->where('Gd_cpdh|成品代号', 'LIKE', rtrim($value['客户编号']) . '%')
-                ->order('Sys_rq DESC')
-                ->find();
-
-            // 如果没有找到相关工单,跳过
-            if (!$productIng || empty($productIng['Sys_rq'])) {
+            $khbh = $productMap[$code]['客户编号'];
+            $khmc = $productMap[$code]['客户名称'];
+            if (empty($khbh) || empty($khmc) || empty($value['latest_ny'])) {
                 continue;
             }
 
-            $name = $value['客户编号'] . '【' . $value['客户名称'] . '】';
-            $year = date('Y', strtotime($productIng['Sys_rq']));
-            $uniqueKey = $value['客户编号'] . '_' . $value['客户名称'] . '_' . $year;
+            // 账期取自 sys_ny(YYYYMM),年份取前4位
+            $latestNy = trim($value['latest_ny']);
+            if (strlen($latestNy) < 6) {
+                continue;
+            }
+            $year = substr($latestNy, 0, 4);
 
-            if (isset($seenEntries[$uniqueKey])) {
-                continue; // 如果已经存在,跳过重复项
+            $key = $khbh . '【' . $khmc . '】';
+            if (!isset($customerYear[$key]) || $year > $customerYear[$key]['year']) {
+                $customerYear[$key] = ['year' => $year, 'khbh' => $khbh];
             }
-            $seenEntries[$uniqueKey] = true;
+        }
 
-            if (strpos($value['客户编号'], 'J') !== false || strpos($value['客户编号'], 'Y') !== false) {
+        $data['翌星工单'] = [];
+        $data['MN工单'] = [];
+        foreach ($customerYear as $name => $info) {
+            $khbh = $info['khbh'];
+            $year = $info['year'];
+            if (strpos($khbh, 'J') !== false || strpos($khbh, 'Y') !== false) {
                 if (!isset($data['翌星工单'][$year])) {
                     $data['翌星工单'][$year] = [];
                 }
@@ -792,21 +807,34 @@ class  Achievementatestatistics extends Api
             $this->error('请求错误');
         }
         $param = $this->request->param();
-        $rq = $param['rq'];
+        $rq = isset($param['rq']) ? trim($param['rq']) : '';
 
         $where = [];
         if (!empty($param['search'])){
             $where['产品代号|产品名称'] = ['like','%'.$param['search'].'%'];
         }
+        // 客户筛选:根据客户编号到产品_基本资料找到对应产品编号,再过滤产品代号
+        $codeFilter = null;
         if (!empty($param['khdh'])){
-            $where['产品代号'] = ['like',$param['khdh'].'%'];
+            $codeFilter = \db('产品_基本资料')
+                ->where('客户编号', 'like', $param['khdh'].'%')
+                ->column('产品编号');
+            if (empty($codeFilter)) {
+                $this->success('成功', []);
+            }
         }
 
-        $qualityData = \db('工单_质量考核汇总')
-            ->field('Gy0_gdbh, 客户代号, 入仓日期 as sys_rq, 实际投料, 入仓数量, 产品代号, 产品名称, 销售订单号, 订单数量,计量单位')
-            ->where('YEAR(Sys_rq)', $rq)
-            ->where($where)
-            ->select();
+        // rq 为空时不限年份,即"整个表"查询
+        $query = \db('工单_质量考核汇总')
+            ->field('Gy0_gdbh, sys_ny, 实际投料, 入仓数量, 产品代号, 产品名称, 销售订单号, 订单数量,计量单位')
+            ->where($where);
+        if ($codeFilter !== null) {
+            $query->whereIn('产品代号', $codeFilter);
+        }
+        if ($rq !== '') {
+            $query->where('sys_ny', 'like', $rq . '%');
+        }
+        $qualityData = $query->select();
         if (empty($qualityData)) {
             $this->success('未查询到数据', []);
         }
@@ -824,14 +852,14 @@ class  Achievementatestatistics extends Api
         $productMap = [];
         foreach ($uniqueByGongdan as $gdbh => $data) {
             $productCode = $data['产品代号'];
-            $sysRq = $data['sys_rq'];
+            $sysNy = trim($data['sys_ny']);
 
-            // 提取月份1-12 的月份数字
-            $month = date('n', strtotime($sysRq));
+            // 从 sys_ny(YYYYMM) 提取月份 1-12
+            $month = (int)substr($sysNy, 4, 2);
 
             if (!isset($productMap[$productCode])) {
                 $productMap[$productCode] = [
-                    'sys_rq' => substr($data['sys_rq'], 0, 4),
+                    'sys_rq' => substr($sysNy, 0, 4),
                     '计量单位' => $data['计量单位'],
                     '成品编码' => $data['产品代号'],
                     '成品名称' => $data['产品名称'],
@@ -942,9 +970,9 @@ class  Achievementatestatistics extends Api
 
         // 1. 查询对应的工单数据
         $qualityData = \db('工单_质量考核汇总')
-            ->field('Gy0_gdbh as 工单编号, 订单数量, 入仓日期, 实际投料, 入仓数量, 客户代号, 客户名称, 产品代号, 产品名称, 销售订单号')
+            ->field('Gy0_gdbh as 工单编号, 订单数量, 入仓日期, sys_ny, 实际投料, 入仓数量, 产品代号, 产品名称, 销售订单号')
             ->where('产品代号', $productCode)
-            ->where('YEAR(入仓日期)', $year)
+            ->where('sys_ny', 'like', $year . '%')
             ->order('入仓日期','desc')
             ->select();
 
@@ -952,6 +980,22 @@ class  Achievementatestatistics extends Api
             $this->success('该产品无质量考核数据', []);
         }
 
+        // 根据产品代号到产品_基本资料获取客户编号和客户名称
+        $codes = array_unique(array_map(function ($item) {
+            return trim($item['产品代号']);
+        }, $qualityData));
+        $productRows = \db('产品_基本资料')
+            ->field('产品编号, 客户编号, 客户名称')
+            ->whereIn('产品编号', $codes)
+            ->select();
+        $productMap = [];
+        foreach ($productRows as $p) {
+            $productMap[trim($p['产品编号'])] = [
+                '客户编号' => trim($p['客户编号']),
+                '客户名称' => trim($p['客户名称'])
+            ];
+        }
+
         // 2. 先按工单去重,每个工单只取一条记录
         $uniqueByGongdan = [];
         foreach ($qualityData as $data) {
@@ -970,19 +1014,22 @@ class  Achievementatestatistics extends Api
 //        ];
 
         foreach ($uniqueByGongdan as $gdbh => $data) {
-            $sysRq = $data['入仓日期'];
-            $month = date('n', strtotime($sysRq)); // 1-12 的月份数字
+            $sysNy = trim($data['sys_ny']);
+            $month = (int)substr($sysNy, 4, 2); // 1-12 的月份数字
 
             // 初始化月份数据
             if (!isset($monthlyData[$data['工单编号']])) {
+                $code = trim($data['产品代号']);
+                $khbh = isset($productMap[$code]) ? $productMap[$code]['客户编号'] : '';
+                $khmc = isset($productMap[$code]) ? $productMap[$code]['客户名称'] : '';
                 $monthlyData[$data['工单编号']] = [
                     '月份' => $month,
                     '订单数量' => 0,
                     '实际投料' => 0,
                     '入仓数量' => 0,
                     '入仓日期' => $data['入仓日期'],
-                    '客户代号' => $data['客户代号'],
-                    '客户名称' => $data['客户名称'],
+                    '客户代号' => $khbh,
+                    '客户名称' => $khmc,
                     '产品代号' => $data['产品代号'],
                     '产品名称' => $data['产品名称'],
                     '销售订单号' => $data['销售订单号']
@@ -1028,4 +1075,289 @@ class  Achievementatestatistics extends Api
         $this->success('成功', array_values($detailList));
     }
 
+    /**
+     * 02.产品月度投入产出率统计->左侧菜单
+     */
+    public function left_Productmonth() {
+        $list = \db('工单_质量考核汇总')
+            ->field('客户代号, 客户名称, sys_ny')
+            ->where('客户代号', '<>', '')
+            ->order('sys_ny desc')
+            ->select();
+
+        $data['翌星工单'] = [];
+        $data['MN工单'] = [];
+        $seenEntries = [];
+
+        foreach ($list as $value) {
+            $khbh = rtrim($value['客户代号']);
+            $khmc = rtrim($value['客户名称']);
+            $ny = trim((string)$value['sys_ny']);
+            if (empty($khmc) || strlen($ny) < 6) {
+                continue;
+            }
+
+            $year = substr($ny, 0, 4);
+            $ym = substr($ny, 0, 6);
+
+            $name = $khbh . '【' . $khmc . '】';
+            $uniqueKey = $khbh . '_' . $khmc . '_' . $ym;
+            if (isset($seenEntries[$uniqueKey])) {
+                continue;
+            }
+            $seenEntries[$uniqueKey] = true;
+
+            if (strpos($khbh, 'J') !== false || strpos($khbh, 'Y') !== false) {
+                $data['翌星工单'][$year][$ym][] = $name;
+            } else {
+                $data['MN工单'][$year][$ym][] = $name;
+            }
+        }
+
+        // 按年份、月份倒序排序
+        krsort($data['翌星工单']);
+        krsort($data['MN工单']);
+
+        foreach ($data as &$years) {
+            foreach ($years as &$months) {
+                krsort($months);
+                foreach ($months as &$items) {
+                    sort($items);
+                }
+                unset($items);
+            }
+            unset($months);
+        }
+        unset($years);
+
+        $this->success('成功', $data);
+    }
+
+    /**
+     * 02.产品月度投入产出率统计->数据汇总表
+     */
+    public function list_Productmonth_hz() {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+        $param = $this->request->param();
+        $ym = trim((string)($param['ym'] ?? ''));
+        $rq = trim((string)($param['rq'] ?? ''));
+
+        // 解析年月:优先使用 ym(YYYYMM),否则回退 year + month
+        if ($ym !== '' && preg_match('/^\d{6}$/', $ym)) {
+            $year = substr($ym, 0, 4);
+            $month = (int)substr($ym, 4, 2);
+        } else {
+            $year = $rq !== '' ? $rq : date('Y');
+            $month = !empty($param['month']) ? (int)$param['month'] : (int)date('n');
+        }
+        // 账期(YYYYMM),以 sys_ny 为准
+        $ny = $year . str_pad((string)$month, 2, '0', STR_PAD_LEFT);
+
+        $where = [];
+        if (!empty($param['search'])) {
+            $where['产品代号|产品名称'] = ['like', '%' . $param['search'] . '%'];
+        }
+        if (!empty($param['khdh'])) {
+            $where['客户代号'] = ['like', $param['khdh'] . '%'];
+        }
+
+        $qualityData = \db('工单_质量考核汇总')
+            ->field('Gy0_gdbh, 客户代号, 客户名称, sys_ny, 实际投料, 入仓数量, 产品代号, 产品名称, 销售订单号, 订单数量, 计量单位')
+            ->where('sys_ny', $ny)
+            ->where($where)
+            ->select();
+
+        if (empty($qualityData)) {
+            $this->success('未查询到数据', []);
+        }
+
+        // 第一步:按工单去重,每个工单只取一条记录
+        $uniqueByGongdan = [];
+        foreach ($qualityData as $data) {
+            $gdbh = $data['Gy0_gdbh'];
+            if (!isset($uniqueByGongdan[$gdbh])) {
+                $uniqueByGongdan[$gdbh] = $data;
+            }
+        }
+
+        // 印件信息(按工单编号)
+        $yjMap = [];
+        $gdbhList = array_keys($uniqueByGongdan);
+        if (!empty($gdbhList)) {
+            $yjList = \db('工单_印件资料')
+                ->field('Yj_Gdbh, Yj_Yjdh, yj_yjmc')
+                ->whereIn('Yj_Gdbh', $gdbhList)
+                ->select();
+            foreach ($yjList as $yj) {
+                $yjMap[$yj['Yj_Gdbh']] = $yj;
+            }
+        }
+
+        // 第二步:按成品编码分组汇总
+        $productMap = [];
+        foreach ($uniqueByGongdan as $gdbh => $data) {
+            $productCode = $data['产品代号'];
+            if (!isset($productMap[$productCode])) {
+                $productMap[$productCode] = [
+                    'sys_rq' => $ny,
+                    '成品编码' => $data['产品代号'],
+                    '成品名称' => $data['产品名称'],
+                    '客户编号' => rtrim($data['客户代号']),
+                    '客户名称' => rtrim($data['客户名称']),
+                    '计量单位' => $data['计量单位'],
+                    '订单数量' => 0,
+                    '实际投料' => 0,
+                    '入仓数量' => 0,
+                    '印件代号' => [],
+                    '印件名称' => [],
+                    '工单列表' => []
+                ];
+            }
+
+            $yj = isset($yjMap[$gdbh]) ? $yjMap[$gdbh] : [];
+            $productMap[$productCode]['印件代号'][] = isset($yj['Yj_Yjdh']) ? rtrim($yj['Yj_Yjdh']) : '';
+            $productMap[$productCode]['印件名称'][] = isset($yj['yj_yjmc']) ? rtrim($yj['yj_yjmc']) : '';
+
+            $productMap[$productCode]['订单数量'] += round($data['订单数量'] * 10000);
+            $productMap[$productCode]['实际投料'] += round($data['实际投料'] * 10000);
+            $productMap[$productCode]['入仓数量'] += $data['入仓数量'];
+            $productMap[$productCode]['工单列表'][] = $data['Gy0_gdbh'];
+        }
+
+        // 第三步:计算投入产出率(入仓数量 / 实际投料)
+        $result = [];
+        foreach ($productMap as $productCode => $productData) {
+            if ($productData['实际投料'] > 0) {
+                $rate = round(($productData['入仓数量'] / $productData['实际投料']) * 100, 2) . '%';
+            } else if ($productData['入仓数量'] > 0) {
+                $rate = '100%';
+            } else {
+                $rate = '0%';
+            }
+
+            $result[] = [
+                'sys_rq' => $productData['sys_rq'],
+                '成品编码' => $productData['成品编码'],
+                '成品名称' => $productData['成品名称'],
+                '印件代号' => implode('、', array_unique(array_filter($productData['印件代号']))),
+                '印件名称' => implode('、', array_unique(array_filter($productData['印件名称']))),
+                '订单数量' => $productData['订单数量'],
+                '实际投料' => $productData['实际投料'],
+                '入仓数量' => $productData['入仓数量'],
+                '投入产出率' => $rate,
+                '计量单位' => $productData['计量单位'],
+                '工单数量' => count($productData['工单列表']),
+                '工单列表' => implode(', ', $productData['工单列表']),
+                '客户编号' => $productData['客户编号'],
+                '客户名称' => $productData['客户名称']
+            ];
+        }
+
+        $this->success('成功', $result);
+    }
+
+    /**
+     * 02.产品月度投入产出率统计->数据明细表
+     */
+    public function list_Productmonth_mx() {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+
+        $param = $this->request->param();
+        $productCode = trim((string)($param['product_code'] ?? ''));
+        $ym = trim((string)($param['ym'] ?? ''));
+        $rq = trim((string)($param['rq'] ?? ''));
+
+        if (empty($productCode)) {
+            $this->error('请提供成品编码');
+        }
+
+        // 解析年月:优先使用 ym(YYYYMM),否则回退 year + month
+        if ($ym !== '' && preg_match('/^\d{6}$/', $ym)) {
+            $year = substr($ym, 0, 4);
+            $month = (int)substr($ym, 4, 2);
+        } else {
+            $year = $rq !== '' ? $rq : date('Y');
+            $month = !empty($param['month']) ? (int)$param['month'] : (int)date('n');
+        }
+        // 账期(YYYYMM),以 sys_ny 为准
+        $ny = $year . str_pad((string)$month, 2, '0', STR_PAD_LEFT);
+
+        $query = \db('工单_质量考核汇总')
+            ->field('Gy0_gdbh as 工单编号, 订单数量, 入仓日期, sys_ny, 实际投料, 入仓数量, 客户代号, 客户名称, 产品代号, 产品名称, 销售订单号')
+            ->where('产品代号', $productCode)
+            ->where('sys_ny', $ny);
+
+        if (!empty($param['khdh'])) {
+            $query->where('客户代号', 'like', $param['khdh'] . '%');
+        }
+
+        $qualityData = $query->order('入仓日期', 'desc')->select();
+
+        if (empty($qualityData)) {
+            $this->success('该产品无质量考核数据', []);
+        }
+
+        // 按工单去重,每个工单只取一条记录
+        $uniqueByGongdan = [];
+        foreach ($qualityData as $data) {
+            $gdbh = $data['工单编号'];
+            if (!isset($uniqueByGongdan[$gdbh])) {
+                $uniqueByGongdan[$gdbh] = $data;
+            }
+        }
+
+        // 印件信息(按工单编号)
+        $yjMap = [];
+        $gdbhList = array_keys($uniqueByGongdan);
+        if (!empty($gdbhList)) {
+            $yjList = \db('工单_印件资料')
+                ->field('Yj_Gdbh, Yj_Yjdh, yj_yjmc, Yj_Yjno')
+                ->whereIn('Yj_Gdbh', $gdbhList)
+                ->select();
+            foreach ($yjList as $yj) {
+                $yjMap[$yj['Yj_Gdbh']] = $yj;
+            }
+        }
+
+        $detailList = [];
+        foreach ($uniqueByGongdan as $gdbh => $data) {
+            $actual = round($data['实际投料'] * 10000);
+            $delivery = round($data['入仓数量']);
+
+            // 投入产出率 = 入仓数量 / 实际投料
+            if ($actual > 0) {
+                $rate = round(($delivery / $actual) * 100, 2) . '%';
+            } else if ($delivery > 0) {
+                $rate = '100%';
+            } else {
+                $rate = '0%';
+            }
+
+            $yj = isset($yjMap[$gdbh]) ? $yjMap[$gdbh] : [];
+
+            $detailList[] = [
+                '工单编号' => $data['工单编号'],
+                '印件号' => isset($yj['Yj_Yjno']) ? rtrim($yj['Yj_Yjno']) : '',
+                '印件代号' => isset($yj['Yj_Yjdh']) ? rtrim($yj['Yj_Yjdh']) : '',
+                '印件名称' => isset($yj['yj_yjmc']) ? rtrim($yj['yj_yjmc']) : '',
+                '订单数量' => round($data['订单数量'] * 10000),
+                '实际投料' => $actual,
+                '入仓数量' => $delivery,
+                '完工时间' => substr($data['入仓日期'], 0, 10),
+                '投入产出率' => $rate,
+                '客户编号' => rtrim($data['客户代号']),
+                '客户名称' => rtrim($data['客户名称']),
+                '成品编码' => $data['产品代号'],
+                '成品名称' => $data['产品名称'],
+                '销售订单号' => $data['销售订单号']
+            ];
+        }
+
+        $this->success('成功', $detailList);
+    }
+
 }

+ 378 - 0
application/api/controller/CustomerFeedback.php

@@ -0,0 +1,378 @@
+<?php
+
+namespace app\api\controller;
+
+use app\common\controller\Api;
+use think\Request;
+
+/**
+ * 客户反馈与投诉记录
+ */
+class CustomerFeedback extends Api
+{
+    protected $noNeedLogin = ['*'];
+    protected $noNeedRight = ['*'];
+
+    /**
+     * 左侧菜单栏(处理中客诉人员 + 年度客诉统计)
+     * @ApiMethod GET
+     * @return void
+     */
+    public function getTab()
+    {
+        if (Request::instance()->isGet() == false) {
+            $this->error('非法请求');
+        }
+
+        // 处理中客诉 —— 按建档人 Sys_id 分组取不重复人员
+        // 已在 db_客诉流程 中存在“处理完毕”环节的客诉视为已关闭,不计入处理中
+        $personList = \db('db_客诉记录')
+            ->whereRaw("UniqID NOT IN (SELECT RelationID FROM db_客诉流程 WHERE rtrim(处理环节) = '处理完毕')")
+            ->where('Sys_id', '<>', '')
+            ->group('Sys_id')
+            ->field('rtrim(Sys_id) as Sys_id')
+            ->order('Sys_id asc')
+            ->select();
+
+        $children = [];
+        foreach ($personList as $item) {
+            $name = $item['Sys_id'];
+            // 拆分 "admin/超级管理员" 格式
+            $parts = explode('/', $name);
+            $code = isset($parts[0]) ? trim($parts[0]) : '';
+            $realName = isset($parts[1]) ? trim($parts[1]) : $name;
+            $children[] = [
+                'label' => $name,
+                'code'  => $code,
+                'name'  => $realName,
+                'type'  => 'person', // 人员节点
+            ];
+        }
+
+        // 处理中客诉
+        $treeData[] = [
+            'label'    => '处理中客诉',
+            'children' => $children,
+            'type'     => 'group',
+        ];
+
+        // 年度客诉统计
+        $treeData[] = [
+            'label' => '年度客诉统计',
+            'type'  => 'year_stat',
+        ];
+
+        $this->success('请求成功', $treeData);
+    }
+
+    /**
+     * 获取右侧表格数据
+     * @ApiMethod GET
+     * @param string code      人员编号(可选)
+     * @param string type      节点类型 person | year_stat(可选)
+     * @return void
+     */
+    public function getList()
+    {
+        if (Request::instance()->isGet() == false) {
+            $this->error('非法请求');
+        }
+        $params = Request::instance()->param();
+
+        $field = 'rtrim(客诉单号) as 客诉单号,rtrim(客诉日期) as 客诉日期,rtrim(客诉方式) as 客诉方式,rtrim(订单编号) as 订单编号,rtrim(产品编号) as 产品编号,rtrim(产品名称) as 产品名称,rtrim(客户编号) as 客户编号,rtrim(客户名称) as 客户名称,rtrim(客诉描述) as 客诉描述,rtrim(缺陷关键字) as 缺陷关键字,rtrim(客诉性质) as 客诉性质,扣分,rtrim(主要责任部门) as 主要责任部门,rtrim(次要责任部门) as 次要责任部门,UniqID,rtrim(Sys_id) as Sys_id,Sys_rq,Mod_rq';
+
+        $nodeType = isset($params['type']) ? $params['type'] : '';
+        $code     = isset($params['code']) ? trim($params['code']) : '';
+        $name     = isset($params['name']) ? trim($params['name']) : '';
+
+        $query = \db('db_客诉记录')->field($field);
+
+        // 已在 db_客诉流程 中存在“处理完毕”环节的客诉视为已关闭
+        $notDoneSql = "UniqID NOT IN (SELECT RelationID FROM db_客诉流程 WHERE rtrim(处理环节) = '处理完毕')";
+
+        if ($nodeType === 'person') {
+            // 处理中客诉 —— 无处理完毕环节,且按建档人 Sys_id 过滤
+            $query->whereRaw($notDoneSql);
+            if (!empty($name)) {
+                $query->whereLike('Sys_id', '%' . $name . '%');
+            }
+        } elseif ($nodeType === 'year_stat') {
+            // 年度客诉统计 —— 查全部
+        } else {
+            // 默认:全部处理中(无处理完毕环节)
+            $query->whereRaw($notDoneSql);
+        }
+
+        $list = $query->order('客诉日期 desc')->select();
+
+        if (empty($list)) {
+            $this->success('暂无数据', []);
+        }
+        $this->success('请求成功', $list);
+    }
+
+    /**
+     * 新增客诉记录
+     * @ApiMethod POST
+     * @return void
+     */
+    public function add()
+    {
+        if (Request::instance()->isPost() == false) {
+            $this->error('非法请求');
+        }
+        $data = Request::instance()->post();
+        if (empty($data)) {
+            $this->error('参数为空');
+        }
+
+        // 自动生成 UniqID(取当前最大+1)
+        $maxId = \db('db_客诉记录')->max('UniqID');
+        $data['UniqID'] = $maxId ? $maxId + 1 : 1;
+
+        // 若客诉日期为空,填当天
+        if (empty($data['客诉日期'])) {
+            $data['客诉日期'] = date('Y-m-d H:i:s');
+        }
+        // 系统字段
+        $data['Sys_rq'] = date('Y-m-d H:i:s');
+        $data['Mod_rq'] = date('Y-m-d H:i:s');
+
+        $sql = \db('db_客诉记录')->fetchSql(true)->insert($data);
+        $res = \db()->query($sql);
+        if ($res === false) {
+            $this->error('新增失败');
+        }
+        $this->success('新增成功', ['UniqID' => $data['UniqID']]);
+    }
+
+    /**
+     * 修改客诉记录
+     * @ApiMethod POST
+     * @return void
+     */
+    public function edit()
+    {
+        if (Request::instance()->isPost() == false) {
+            $this->error('非法请求');
+        }
+        $data = Request::instance()->post();
+        if (empty($data['UniqID'])) {
+            $this->error('缺少 UniqID');
+        }
+
+        $data['Mod_rq'] = date('Y-m-d H:i:s');
+
+        $uniqId = $data['UniqID'];
+        unset($data['UniqID']);
+        $sql = \db('db_客诉记录')->where('UniqID', $uniqId)->fetchSql(true)->update($data);
+        $res = \db()->query($sql);
+        if ($res === false) {
+            $this->error('修改失败');
+        }
+        $this->success('修改成功');
+    }
+
+    /**
+     * 删除客诉记录(支持批量)
+     * @ApiMethod POST
+     * @param  UniqID  单个 UniqID 或者 UniqID 数组
+     * @return void
+     */
+    public function del()
+    {
+        if (Request::instance()->isPost() == false) {
+            $this->error('非法请求');
+        }
+        $params = Request::instance()->post();
+        if (empty($params['UniqID']) && empty($params['ids'])) {
+            $this->error('参数错误');
+        }
+
+        if (!empty($params['ids'])) {
+            // 批量删除
+            $ids = is_array($params['ids']) ? $params['ids'] : explode(',', $params['ids']);
+            $res = \db('db_客诉记录')->whereIn('UniqID', $ids)->delete();
+        } else {
+            $res = \db('db_客诉记录')->where('UniqID', $params['UniqID'])->delete();
+        }
+        if ($res === false) {
+            $this->error('删除失败');
+        }
+        $this->success('删除成功');
+    }
+
+    // =====================================================
+    // 以下为处理环节记录 (db_客诉流程) 和 相关整改附件 (db_客诉附件) 接口
+    // =====================================================
+
+    /**
+     * 获取处理环节记录列表
+     * @ApiMethod GET
+     * @param int RelationID  关联主表 UniqID
+     * @return void
+     */
+    public function getFlowList()
+    {
+        if (Request::instance()->isGet() == false) {
+            $this->error('非法请求');
+        }
+        $params = Request::instance()->param();
+        if (empty($params['RelationID'])) {
+            $this->error('缺少 RelationID');
+        }
+
+        $field = 'rtrim(RelationID) as RelationID,rtrim(操作者) as 操作者,rtrim(处理环节) as 处理环节,rtrim(备注说明) as 备注说明,sys_id,sys_rq,mod_rq,UniqId';
+        $list = \db('db_客诉流程')
+            ->where('RelationID', intval($params['RelationID']))
+            ->field($field)
+            ->order('UniqId asc')
+            ->select();
+
+        $this->success('请求成功', $list ?: []);
+    }
+
+    /**
+     * 新增处理环节记录
+     * @ApiMethod POST
+     * @return void
+     */
+    public function addFlow()
+    {
+        if (Request::instance()->isPost() == false) {
+            $this->error('非法请求');
+        }
+        $data = Request::instance()->post();
+        if (empty($data['RelationID'])) {
+            $this->error('缺少 RelationID');
+        }
+
+        // 自动生成 UniqId
+        $maxId = \db('db_客诉流程')->max('UniqId');
+        $data['UniqId'] = $maxId ? $maxId + 1 : 1;
+
+        $data['sys_rq'] = date('Y-m-d H:i:s');
+        $data['mod_rq'] = date('Y-m-d H:i:s');
+
+        $sql = \db('db_客诉流程')->fetchSql(true)->insert($data);
+        $res = \db()->query($sql);
+        if ($res === false) {
+            $this->error('新增处理环节失败');
+        }
+        $this->success('新增成功', ['UniqId' => $data['UniqId']]);
+    }
+
+    /**
+     * 删除处理环节记录
+     * @ApiMethod POST
+     * @param int UniqId
+     * @return void
+     */
+    public function delFlow()
+    {
+        if (Request::instance()->isPost() == false) {
+            $this->error('非法请求');
+        }
+        $params = Request::instance()->post();
+        if (empty($params['UniqId'])) {
+            $this->error('缺少 UniqId');
+        }
+
+        $res = \db('db_客诉流程')->where('UniqId', intval($params['UniqId']))->delete();
+        if ($res === false) {
+            $this->error('删除失败');
+        }
+        $this->success('删除成功');
+    }
+
+    /**
+     * 获取整改附件列表
+     * @ApiMethod GET
+     * @param int relationId  关联主表 UniqID
+     * @return void
+     */
+    public function getAttachmentList()
+    {
+        if (Request::instance()->isGet() == false) {
+            $this->error('非法请求');
+        }
+        $params = Request::instance()->param();
+        if (empty($params['relationId'])) {
+            $this->error('缺少 relationId');
+        }
+
+        $field = 'relationId,名称及路径,修订日期,附件类型,sys_id,sys_rq,mod_rq,UniqId';
+        $list = \db('db_客诉附件')
+            ->where('relationId', intval($params['relationId']))
+            ->field($field)
+            ->order('UniqId asc')
+            ->select();
+
+        $this->success('请求成功', $list ?: []);
+    }
+
+    /**
+     * 新增整改附件
+     * @ApiMethod POST (FormData)
+     * @return void
+     */
+    public function addAttachment()
+    {
+        if (Request::instance()->isPost() == false) {
+            $this->error('非法请求');
+        }
+        $data = Request::instance()->post();
+        if (empty($data['relationId'])) {
+            $this->error('缺少 relationId');
+        }
+        if (empty($data['名称及路径'])) {
+            $this->error('缺少 名称及路径');
+        }
+
+        // 自动生成 UniqId
+        $maxId = \db('db_客诉附件')->max('UniqId');
+        $data['UniqId'] = $maxId ? $maxId + 1 : 1;
+
+        $data['修订日期'] = date('Y-m-d H:i:s');
+        $data['sys_rq'] = date('Y-m-d H:i:s');
+        $data['mod_rq'] = date('Y-m-d H:i:s');
+
+        // 附件内容是 base64,直接存入 longblob
+        if (!empty($data['附件内容'])) {
+            // 去掉 data:xxx;base64, 前缀
+            if (preg_match('/^data:[^;]+;base64,(.*)$/', $data['附件内容'], $m)) {
+                $data['附件内容'] = base64_decode($m[1]);
+            }
+        }
+
+        $sql = \db('db_客诉附件')->fetchSql(true)->insert($data);
+        $res = \db()->query($sql);
+        if ($res === false) {
+            $this->error('新增附件失败');
+        }
+        $this->success('新增成功', ['UniqId' => $data['UniqId']]);
+    }
+
+    /**
+     * 删除整改附件
+     * @ApiMethod POST
+     * @param int UniqId
+     * @return void
+     */
+    public function delAttachment()
+    {
+        if (Request::instance()->isPost() == false) {
+            $this->error('非法请求');
+        }
+        $params = Request::instance()->post();
+        if (empty($params['UniqId'])) {
+            $this->error('缺少 UniqId');
+        }
+
+        $res = \db('db_客诉附件')->where('UniqId', intval($params['UniqId']))->delete();
+        if ($res === false) {
+            $this->error('删除失败');
+        }
+        $this->success('删除成功');
+    }
+}

+ 1709 - 0
application/api/controller/Decision.php

@@ -1080,4 +1080,1713 @@ class Decision extends Api
             $this->error('插入数据失败');
         }
     }
+
+    /**
+     * 成品入仓印件名称分类
+     * 含“小盒” -> 小盒;含“面彩/围条/内贴/上盖/下盖” -> 其他;其余 -> 条盒
+     */
+    private function CprcCategory($cpmc)
+    {
+        $cpmc = trim((string)$cpmc);
+        if ($cpmc === '') {
+            return '条盒';
+        }
+        if (strpos($cpmc, '小盒') !== false) {
+            return '小盒';
+        }
+        foreach (['面彩', '围条', '内贴', '上盖', '下盖'] as $kw) {
+            if (strpos($cpmc, $kw) !== false) {
+                return '其他';
+            }
+        }
+        return '条盒';
+    }
+
+    /**
+     * 取成品入仓指定账期(年月)的入仓记录
+     * @param string $ny 6位年月(YYYYMM) 或 4位年份(YYYY)
+     */
+    private function CprcMonthRows($ny)
+    {
+        $ny = (string)$ny;
+        if (strlen($ny) === 4) {
+            $year = (int)$ny;
+            $start = $year . '-01-01 00:00:00';
+            $end = ($year + 1) . '-01-01 00:00:00';
+        } else {
+            $year = (int)substr($ny, 0, 4);
+            $month = (int)substr($ny, 4, 2);
+            $start = date('Y-m-01 00:00:00', mktime(0, 0, 0, $month, 1, $year));
+            $end = date('Y-m-01 00:00:00', mktime(0, 0, 0, $month + 1, 1, $year));
+        }
+
+        return \db('成品入仓')
+            ->field('jjcp_gdbh, jjcp_yjno, jjcp_cpdh, jjcp_cpmc, jjcp_sl, jjcp_dw, jjcp_sj')
+            ->where('jjcp_sj', '>=', $start)
+            ->where('jjcp_sj', '<', $end)
+            ->order('jjcp_sj desc')
+            ->select();
+    }
+
+    /**
+     * 成品入仓统计左侧菜单(年 -> 年月,值为入仓数量合计/10000)
+     */
+    public function CprctjLeft()
+    {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+
+        $rows = \db('成品入仓')
+            ->field('jjcp_sj, jjcp_cpmc, jjcp_sl')
+            ->whereNotNull('jjcp_sj')
+            ->select();
+
+        // 先按月聚合
+        $months = [];
+        foreach ($rows as $row) {
+            $sj = trim((string)$row['jjcp_sj']);
+            if ($sj === '') {
+                continue;
+            }
+            $ny = substr(str_replace('-', '', substr($sj, 0, 10)), 0, 6);
+            if (!preg_match('/^\d{6}$/', $ny)) {
+                continue;
+            }
+
+            $cat = $this->CprcCategory($row['jjcp_cpmc']);
+            if ($cat === '其他') {
+                continue;
+            }
+
+            if (!isset($months[$ny])) {
+                $months[$ny] = ['小盒' => 0, '条盒' => 0];
+            }
+            $months[$ny][$cat] += (float)$row['jjcp_sl'];
+        }
+        krsort($months);
+
+        // 再按年聚合
+        $years = [];
+        foreach ($months as $ny => $item) {
+            $year = substr((string)$ny, 0, 4);
+            if (!isset($years[$year])) {
+                $years[$year] = ['小盒' => 0, '条盒' => 0, '月份' => []];
+            }
+            $years[$year]['小盒'] += $item['小盒'];
+            $years[$year]['条盒'] += $item['条盒'];
+            $years[$year]['月份'][] = [
+                '年月' => (string)$ny,
+                '小盒' => round($item['小盒'] / 10000, 3),
+                '条盒' => round($item['条盒'] / 10000, 3),
+            ];
+        }
+        krsort($years);
+
+        $data = [];
+        foreach ($years as $year => $item) {
+            $data[] = [
+                '年份' => (string)$year,
+                '小盒' => round($item['小盒'] / 10000, 2),
+                '条盒' => round($item['条盒'] / 10000, 2),
+                '月份' => $item['月份'],
+            ];
+        }
+
+        $this->success('成功', $data);
+    }
+
+    /**
+     * 成品入仓统计上方表格(按日期汇总)
+     */
+    public function CprctjList_hz()
+    {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+
+        $param = $this->request->param();
+        $ny = trim((string)(isset($param['ym']) ? $param['ym'] : ''));
+        if (!preg_match('/^\d{4}(\d{2})?$/', $ny)) {
+            $this->error('参数错误');
+        }
+
+        $rows = $this->CprcMonthRows($ny);
+
+        $days = [];
+        foreach ($rows as $row) {
+            $day = substr(trim((string)$row['jjcp_sj']), 0, 10);
+            if (!isset($days[$day])) {
+                $days[$day] = [
+                    '日期' => $day,
+                    '小盒入仓数' => 0,
+                    '条盒入仓数' => 0,
+                    '其他类' => 0,
+                    '入仓数量' => 0,
+                ];
+            }
+
+            $cat = $this->CprcCategory($row['jjcp_cpmc']);
+            $sl = (float)$row['jjcp_sl'];
+
+            if ($cat === '小盒') {
+                $days[$day]['小盒入仓数'] += $sl;
+            } elseif ($cat === '其他') {
+                $days[$day]['其他类'] += $sl;
+            } else {
+                $days[$day]['条盒入仓数'] += $sl;
+            }
+            $days[$day]['入仓数量'] += $sl;
+        }
+        krsort($days);
+
+        $this->success('成功', array_values($days));
+    }
+
+    /**
+     * 成品入仓统计下方表格(工单 + 印件明细)
+     * 客户信息成品入仓表中没有,取自 工单_基本资料
+     */
+    public function CprctjList_mx()
+    {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+
+        $param = $this->request->param();
+        $ny = trim((string)(isset($param['ym']) ? $param['ym'] : ''));
+        if (!preg_match('/^\d{4}(\d{2})?$/', $ny)) {
+            $this->error('参数错误');
+        }
+        $date = trim((string)(isset($param['date']) ? $param['date'] : ''));
+
+        $rows = $this->CprcMonthRows($ny);
+
+        $list = [];
+        $gdbhList = [];
+        foreach ($rows as $row) {
+            $day = substr(trim((string)$row['jjcp_sj']), 0, 10);
+            if ($date !== '' && $day !== $date) {
+                continue;
+            }
+
+            $gdbh = trim((string)$row['jjcp_gdbh']);
+            $key = $gdbh . '|' . trim((string)$row['jjcp_cpdh']) . '|' . trim((string)$row['jjcp_cpmc']) . '|' . $day;
+
+            if (!isset($list[$key])) {
+                $list[$key] = [
+                    '工单编号' => $gdbh,
+                    '印件代号' => trim((string)$row['jjcp_cpdh']),
+                    '印件名称' => trim((string)$row['jjcp_cpmc']),
+                    '日期' => $day,
+                    '小盒数' => 0,
+                    '条盒数' => 0,
+                    '其他类' => 0,
+                    '入仓数量' => 0,
+                    '单位' => trim((string)$row['jjcp_dw']),
+                    '客户编号' => '',
+                    '客户名称' => ''
+                ];
+                if ($gdbh !== '') {
+                    $gdbhList[$gdbh] = 1;
+                }
+            }
+
+            $cat = $this->CprcCategory($row['jjcp_cpmc']);
+            $sl = (float)$row['jjcp_sl'];
+
+            if ($cat === '小盒') {
+                $list[$key]['小盒数'] += $sl;
+            } elseif ($cat === '其他') {
+                $list[$key]['其他类'] += $sl;
+            } else {
+                $list[$key]['条盒数'] += $sl;
+            }
+            $list[$key]['入仓数量'] += $sl;
+        }
+
+        // 客户信息:按工单编号取最新一条工单_基本资料
+        if (!empty($gdbhList)) {
+            $orders = \db('工单_基本资料')
+                ->field('Gd_gdbh, Gd_客户代号, Gd_客户名称')
+                ->whereIn('Gd_gdbh', array_keys($gdbhList))
+                ->order('Sys_rq desc')
+                ->select();
+
+            $customerMap = [];
+            foreach ($orders as $order) {
+                $gdbh = trim((string)$order['Gd_gdbh']);
+                if (!isset($customerMap[$gdbh])) {
+                    $customerMap[$gdbh] = [
+                        '编号' => trim((string)$order['Gd_客户代号']),
+                        '名称' => trim((string)$order['Gd_客户名称'])
+                    ];
+                }
+            }
+
+            foreach ($list as $key => $item) {
+                if (isset($customerMap[$item['工单编号']])) {
+                    $list[$key]['客户编号'] = $customerMap[$item['工单编号']]['编号'];
+                    $list[$key]['客户名称'] = $customerMap[$item['工单编号']]['名称'];
+                }
+            }
+        }
+
+        $data = array_values($list);
+        usort($data, function ($a, $b) {
+            if ($a['日期'] !== $b['日期']) {
+                return strcmp($b['日期'], $a['日期']);
+            }
+            return strcmp($a['工单编号'], $b['工单编号']);
+        });
+
+        $this->success('成功', $data);
+    }
+
+    /**
+     * 成品编码对应的客户信息(产品_基本资料)
+     */
+    private function CprcProductCustomer($codes)
+    {
+        $map = [];
+        $codes = array_values(array_unique(array_filter($codes, function ($code) {
+            return trim((string)$code) !== '';
+        })));
+        if (empty($codes)) {
+            return $map;
+        }
+
+        $rows = \db('产品_基本资料')
+            ->field('产品编号, 客户编号, 客户名称')
+            ->whereIn('产品编号', $codes)
+            ->select();
+
+        foreach ($rows as $row) {
+            $code = trim((string)$row['产品编号']);
+            if ($code === '' || isset($map[$code])) {
+                continue;
+            }
+            $map[$code] = [
+                '客户编号' => trim((string)$row['客户编号']),
+                '客户名称' => trim((string)$row['客户名称']),
+            ];
+        }
+
+        return $map;
+    }
+
+    /**
+     * 年度成品入仓统计左侧菜单(年 -> 客户)
+     */
+    public function YearcprctjLeft()
+    {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+
+        $rows = \db('成品入仓')
+            ->field([
+                "DATE_FORMAT(jjcp_sj, '%Y') AS 年份",
+                '成品编码',
+            ])
+            ->where('jjcp_sj', '>=', '2000-01-01')
+            ->group('年份, 成品编码')
+            ->select();
+
+        $customerMap = $this->CprcProductCustomer(array_column($rows, '成品编码'));
+
+        $years = [];
+        foreach ($rows as $row) {
+            $year = trim((string)$row['年份']);
+            $code = trim((string)$row['成品编码']);
+            if ($year === '' || $year === '0' || !isset($customerMap[$code])) {
+                continue;
+            }
+            $customer = $customerMap[$code];
+            if ($customer['客户名称'] === '') {
+                continue;
+            }
+            if (!isset($years[$year])) {
+                $years[$year] = ['年份' => $year, '客户' => []];
+            }
+            $customerKey = $customer['客户编号'] !== '' ? $customer['客户编号'] : $customer['客户名称'];
+            $years[$year]['客户'][$customerKey] = [
+                '客户编号' => $customer['客户编号'],
+                '客户名称' => $customer['客户名称'],
+            ];
+        }
+        krsort($years);
+
+        $data = [];
+        foreach ($years as $year) {
+            ksort($year['客户']);
+            $year['客户'] = array_values($year['客户']);
+            $data[] = $year;
+        }
+
+        $this->success('成功', $data);
+    }
+
+    /**
+     * 年度成品入仓统计右侧表格
+     * 产品取自成品入仓(成品编码/成品名称),大箱数取自 db_包装计件 的 sczl_cl1-6,按 sczl_rq 月份汇总
+     */
+    public function YearcprctjList()
+    {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+
+        $param = $this->request->param();
+        $year = trim((string)(isset($param['year']) ? $param['year'] : ''));
+        if (!preg_match('/^\d{4}$/', $year)) {
+            $this->error('参数错误');
+        }
+        $customer = trim((string)(isset($param['customer']) ? $param['customer'] : ''));
+        $search = trim((string)(isset($param['search']) ? $param['search'] : ''));
+
+        $start = $year . '-01-01 00:00:00';
+        $end = ((int)$year + 1) . '-01-01 00:00:00';
+
+        // 1、成品入仓:本年度有入仓记录的产品
+        $warehouseRows = \db('成品入仓')
+            ->field('jjcp_gdbh, 成品编码, 成品名称')
+            ->where('jjcp_sj', '>=', $start)
+            ->where('jjcp_sj', '<', $end)
+            ->where('jjcp_gdbh', '<>', '')
+            ->select();
+
+        $products = [];      // 产品编号 => 行数据
+        $orderProduct = [];  // 工单编号(大写) => 产品编号
+        foreach ($warehouseRows as $row) {
+            $code = trim((string)$row['成品编码']);
+            if ($code === '') {
+                continue;
+            }
+            if (!isset($products[$code])) {
+                $name = trim((string)$row['成品名称']);
+                $products[$code] = [
+                    '产品编号' => $code,
+                    '产品名称' => $name,
+                    '产品类别' => strpos($name, '小盒') !== false ? '小盒' : '条盒',
+                    '客户编号' => '',
+                    '客户名称' => '',
+                    'monthly' => array_fill(1, 12, 0),
+                ];
+            }
+
+            $order = strtoupper(trim((string)$row['jjcp_gdbh']));
+            if ($order !== '' && !isset($orderProduct[$order])) {
+                $orderProduct[$order] = $code;
+            }
+        }
+
+        if (empty($products)) {
+            $this->success('成功', []);
+        }
+
+        // 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)
+            ->select();
+
+        foreach ($packRows as $row) {
+            $rq = str_replace('/', '-', trim((string)$row['sczl_rq']));
+            $month = (int)substr($rq, 5, 2);
+            if ($month < 1 || $month > 12) {
+                continue;
+            }
+            for ($i = 1; $i <= 6; $i++) {
+                $order = strtoupper(trim((string)$row['sczl_gdbh' . $i]));
+                if ($order === '' || !isset($orderProduct[$order])) {
+                    continue;
+                }
+                $products[$orderProduct[$order]]['monthly'][$month] += (float)$row['sczl_cl' . $i];
+            }
+        }
+
+        // 3、客户信息:产品_基本资料(按成品编码)
+        $customerMap = $this->CprcProductCustomer(array_keys($products));
+        foreach ($products as $code => $product) {
+            if (isset($customerMap[$code])) {
+                $products[$code]['客户编号'] = $customerMap[$code]['客户编号'];
+                $products[$code]['客户名称'] = $customerMap[$code]['客户名称'];
+            }
+        }
+
+        // 4、组装数据:无数据的月份留空
+        $data = [];
+        foreach ($products as $product) {
+            if ($customer !== '' && $product['客户编号'] !== $customer) {
+                continue;
+            }
+            if ($search !== ''
+                && strpos($product['产品编号'], $search) === false
+                && strpos($product['产品名称'], $search) === false) {
+                continue;
+            }
+
+            $total = 0;
+            $months = [];
+            for ($m = 1; $m <= 12; $m++) {
+                $value = $product['monthly'][$m];
+                $total += $value;
+                $months[str_pad($m, 2, '0', STR_PAD_LEFT) . '月'] = $value > 0 ? round($value, 2) : '';
+            }
+
+            $data[] = array_merge([
+                '产品编号' => $product['产品编号'],
+                '产品名称' => $product['产品名称'],
+                '产品类别' => $product['产品类别'],
+                '每月合计' => round($total, 2),
+            ], $months, [
+                '客户编号' => $product['客户编号'],
+                '客户名称' => $product['客户名称'],
+            ]);
+        }
+
+        usort($data, function ($a, $b) {
+            return strcmp($a['产品编号'], $b['产品编号']);
+        });
+
+        // 5、底部合计行:小盒合计、条盒合计
+        $totalRows = [];
+        foreach (['小盒', '条盒'] as $category) {
+            $exists = false;
+            $total = 0;
+            $sums = array_fill(1, 12, 0);
+            foreach ($data as $row) {
+                if ($row['产品类别'] !== $category) {
+                    continue;
+                }
+                $exists = true;
+                $total += (float)$row['每月合计'];
+                for ($m = 1; $m <= 12; $m++) {
+                    $monthKey = str_pad($m, 2, '0', STR_PAD_LEFT) . '月';
+                    $sums[$m] += $row[$monthKey] === '' ? 0 : (float)$row[$monthKey];
+                }
+            }
+            if (!$exists) {
+                continue;
+            }
+
+            $totalRow = [
+                '产品编号' => '',
+                '产品名称' => $category . '合计(大箱)',
+                '产品类别' => '',
+                '每月合计' => round($total, 2),
+                '合计类型' => $category,
+            ];
+            for ($m = 1; $m <= 12; $m++) {
+                $monthKey = str_pad($m, 2, '0', STR_PAD_LEFT) . '月';
+                $totalRow[$monthKey] = $sums[$m] > 0 ? round($sums[$m], 2) : '';
+            }
+            $totalRow['客户编号'] = '';
+            $totalRow['客户名称'] = '';
+            $totalRows[] = $totalRow;
+        }
+        $data = array_merge($data, $totalRows);
+
+        $this->success('成功', $data);
+    }
+
+    /**
+     * 客诉质量缺陷统计A 左侧菜单(年 -> 缺陷关键字)
+     */
+    public function KhtjLeftA()
+    {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+
+        $rows = \db('db_客诉记录')
+            ->field("DATE_FORMAT(客诉日期, '%Y') AS 年份, rtrim(缺陷关键字) AS 缺陷关键字, count(1) AS num")
+            ->group("DATE_FORMAT(客诉日期, '%Y'), rtrim(缺陷关键字)")
+            ->select();
+
+        $years = [];
+        foreach ($rows as $row) {
+            $year = trim((string)$row['年份']);
+            if ($year === '' || $year === '0') {
+                continue;
+            }
+            if (!isset($years[$year])) {
+                $years[$year] = ['总数' => 0, '关键字' => []];
+            }
+            $num = (int)$row['num'];
+            $years[$year]['总数'] += $num;
+            $keyword = trim((string)$row['缺陷关键字']);
+            if ($keyword !== '') {
+                $years[$year]['关键字'][$keyword] = $num;
+            }
+        }
+        krsort($years);
+
+        $data = [];
+        foreach ($years as $year => $info) {
+            arsort($info['关键字']);
+            $children = [];
+            foreach ($info['关键字'] as $keyword => $num) {
+                $children[] = ['关键字' => $keyword, '次数' => $num];
+            }
+            $data[] = [
+                '年份' => $year,
+                '次数' => $info['总数'],
+                'children' => $children,
+            ];
+        }
+
+        $this->success('成功', $data);
+    }
+
+    /**
+     * 客诉质量缺陷统计A 明细(年 + 缺陷关键字筛选)
+     */
+    public function KhtjListA()
+    {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+
+        $param = $this->request->param();
+        $year = trim((string)(isset($param['year']) ? $param['year'] : ''));
+        if (!preg_match('/^\d{4}$/', $year)) {
+            $this->error('参数错误');
+        }
+        $keyword = trim((string)(isset($param['keyword']) ? $param['keyword'] : ''));
+        $search = trim((string)(isset($param['search']) ? $param['search'] : ''));
+
+        $data = $this->KhtjDetailRows(
+            $year . '-01-01 00:00:00',
+            ((int)$year + 1) . '-01-01 00:00:00',
+            '',
+            $keyword,
+            $search
+        );
+
+        $this->success('成功', $data);
+    }
+
+    /**
+     * 客诉质量缺陷统计B 左侧菜单(年 -> 客户)
+     */
+    public function KhtjLeftB()
+    {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+
+        $rows = \db('db_客诉记录')
+            ->field("DATE_FORMAT(客诉日期, '%Y') AS 年份, rtrim(客户编号) AS 客户编号, rtrim(客户名称) AS 客户名称")
+            ->group("DATE_FORMAT(客诉日期, '%Y'), rtrim(客户编号), rtrim(客户名称)")
+            ->select();
+
+        $years = [];
+        foreach ($rows as $row) {
+            $year = trim((string)$row['年份']);
+            $code = trim((string)$row['客户编号']);
+            $name = trim((string)$row['客户名称']);
+            if ($year === '' || $year === '0' || $code === '') {
+                continue;
+            }
+            if (!isset($years[$year])) {
+                $years[$year] = [];
+            }
+            if (!isset($years[$year][$code]) && $name !== '') {
+                $years[$year][$code] = $name;
+            }
+        }
+        krsort($years);
+
+        $data = [];
+        foreach ($years as $year => $customers) {
+            ksort($customers);
+            $children = [];
+            foreach ($customers as $code => $name) {
+                $children[] = ['客户编号' => $code, '客户名称' => $name];
+            }
+            $data[] = ['年份' => $year, '客户' => $children];
+        }
+
+        $this->success('成功', $data);
+    }
+
+    /**
+     * 客诉质量缺陷统计B 月度汇总 + 明细
+     */
+    public function KhtjListB()
+    {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+
+        $param = $this->request->param();
+        $year = trim((string)(isset($param['year']) ? $param['year'] : ''));
+        if (!preg_match('/^\d{4}$/', $year)) {
+            $this->error('参数错误');
+        }
+        $customer = trim((string)(isset($param['customer']) ? $param['customer'] : ''));
+        $search = trim((string)(isset($param['search']) ? $param['search'] : ''));
+
+        $start = $year . '-01-01 00:00:00';
+        $end = ((int)$year + 1) . '-01-01 00:00:00';
+
+        // 1、月度汇总:按客户统计全年及每月客诉次数(按客诉日期所在月份)
+        $summary = $this->KhtjSummaryRows($start, $end, $customer, $search);
+
+        // 2、客诉明细
+        $list = $this->KhtjDetailRows($start, $end, $customer, '', $search);
+
+        $this->success('成功', ['summary' => $summary, 'list' => $list]);
+    }
+
+    /**
+     * 客诉月度汇总(按客户统计全年及每月客诉次数)
+     */
+    private function KhtjSummaryRows($start, $end, $customer = '', $search = '')
+    {
+        $rows = \db('db_客诉记录')
+            ->field("rtrim(客户编号) AS 客户编号, rtrim(客户名称) AS 客户名称, DATE_FORMAT(客诉日期, '%m') AS 月")
+            ->where('客诉日期', '>=', $start)
+            ->where('客诉日期', '<', $end)
+            ->select();
+
+        $customers = [];
+        foreach ($rows as $row) {
+            $code = trim((string)$row['客户编号']);
+            if ($code === '') {
+                continue;
+            }
+            $month = (int)$row['月'];
+            if ($month < 1 || $month > 12) {
+                continue;
+            }
+            if (!isset($customers[$code])) {
+                $customers[$code] = [
+                    '客户名称' => trim((string)$row['客户名称']),
+                    '总数' => 0,
+                    'monthly' => array_fill(1, 12, 0),
+                ];
+            }
+            $customers[$code]['总数']++;
+            $customers[$code]['monthly'][$month]++;
+        }
+
+        $year = substr($start, 0, 4);
+        $summary = [];
+        foreach ($customers as $code => $info) {
+            if ($customer !== '' && $code !== $customer) {
+                continue;
+            }
+            if ($search !== '' && mb_stripos($code . ' ' . $info['客户名称'], $search) === false) {
+                continue;
+            }
+            $summaryRow = [
+                '年月' => $year,
+                '客户编号' => $code,
+                '客户名称' => $info['客户名称'],
+                '年度投诉次数' => $info['总数'],
+            ];
+            for ($m = 1; $m <= 12; $m++) {
+                $summaryRow['月份' . str_pad($m, 2, '0', STR_PAD_LEFT)] = $info['monthly'][$m] > 0 ? $info['monthly'][$m] : '';
+            }
+            $summary[] = $summaryRow;
+        }
+        usort($summary, function ($a, $b) {
+            return strcmp($a['客户编号'], $b['客户编号']);
+        });
+
+        return $summary;
+    }
+
+    /**
+     * 客诉明细查询(统计A/B共用)
+     */
+    private function KhtjDetailRows($start, $end, $customer = '', $keyword = '', $search = '')
+    {
+        $field = 'rtrim(客诉单号) AS 客诉单号, 客诉日期, rtrim(客诉方式) AS 客诉方式, rtrim(订单编号) AS 订单编号, '
+            . 'rtrim(产品编号) AS 产品编号, rtrim(产品名称) AS 产品名称, rtrim(客户编号) AS 客户编号, rtrim(客户名称) AS 客户名称, '
+            . 'rtrim(客诉描述) AS 客诉描述, rtrim(缺陷关键字) AS 缺陷关键字, rtrim(客诉性质) AS 客诉性质, 扣分, '
+            . 'rtrim(主要责任部门) AS 主要责任部门, rtrim(次要责任部门) AS 次要责任部门, rtrim(Sys_id) AS 创建用户, '
+            . 'Sys_rq AS 创建时间, 关闭时间 AS 结案时间, UniqID';
+
+        $query = \db('db_客诉记录')
+            ->field($field)
+            ->where('客诉日期', '>=', $start)
+            ->where('客诉日期', '<', $end);
+        if ($customer !== '') {
+            $query->where('客户编号', $customer);
+        }
+        if ($keyword !== '') {
+            $query->where('缺陷关键字', $keyword);
+        }
+        if ($search !== '') {
+            $query->where('客诉单号|订单编号|产品编号|产品名称|客户编号|客户名称|客诉描述|缺陷关键字', 'like', '%' . $search . '%');
+        }
+
+        return $query->order('客诉日期 desc')->select();
+    }
+
+    /**
+     * 年度打样效率统计 左侧菜单(年 -> 年月)
+     */
+    public function DyxlLeft()
+    {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+
+        $list = \db('工单_基本资料')
+            ->field([
+                "DATE_FORMAT(工单完工日期, '%Y') AS 年份",
+                "DATE_FORMAT(工单完工日期, '%Y%m') AS 年月",
+            ])
+            ->where('gd_statu', '1-已完工')
+            ->whereRaw($this->DyxlOrderWhere())
+            ->whereRaw('工单完工日期 IS NOT NULL')
+            ->group("DATE_FORMAT(工单完工日期, '%Y'), DATE_FORMAT(工单完工日期, '%Y%m')")
+            ->orderRaw("DATE_FORMAT(工单完工日期, '%Y%m') DESC")
+            ->select();
+
+        $years = [];
+        foreach ($list as $row) {
+            $year = trim((string)$row['年份']);
+            $ym = trim((string)$row['年月']);
+            if ($year === '' || $ym === '') {
+                continue;
+            }
+            if (!isset($years[$year])) {
+                $years[$year] = [];
+            }
+            if (!in_array($ym, $years[$year], true)) {
+                $years[$year][] = $ym;
+            }
+        }
+
+        $data = [];
+        foreach ($years as $year => $months) {
+            rsort($months);
+            $data[] = ['年份' => (string)$year, '月份' => $months];
+        }
+        usort($data, function ($a, $b) {
+            return strcmp($b['年份'], $a['年份']);
+        });
+
+        $this->success('成功', $data);
+    }
+
+    /**
+     * 年度打样效率统计 汇总 + 明细
+     */
+    public function DyxlList()
+    {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+
+        $param = $this->request->param();
+        $date = trim((string)(isset($param['date']) ? $param['date'] : ''));
+        if (!preg_match('/^(\d{4})(\d{2})?$/', $date, $match)) {
+            $this->error('参数错误');
+        }
+
+        $year = (int)$match[1];
+        if (isset($match[2]) && $match[2] !== '') {
+            $month = (int)$match[2];
+            if ($month < 1 || $month > 12) {
+                $this->error('参数错误');
+            }
+            $start = sprintf('%04d-%02d-01', $year, $month);
+            if ($month === 12) {
+                $end = sprintf('%04d-01-01', $year + 1);
+            } else {
+                $end = sprintf('%04d-%02d-01', $year, $month + 1);
+            }
+        } else {
+            $start = sprintf('%04d-01-01', $year);
+            $end = sprintf('%04d-01-01', $year + 1);
+        }
+
+        // 1、打样工单(按工单编号去重)
+        $orders = \db('工单_基本资料')
+            ->field([
+                "RTRIM(Gd_gdbh) AS 工单编号",
+                "DATE_FORMAT(工单完工日期, '%Y%m') AS 年月",
+                "RTRIM(Gd_客户代号) AS 客户编号",
+                "RTRIM(Gd_客户名称) AS 客户名称",
+                "RTRIM(成品名称) AS 成品名称",
+            ])
+            ->where('gd_statu', '1-已完工')
+            ->where('工单完工日期', '>=', $start)
+            ->where('工单完工日期', '<', $end)
+            ->whereRaw($this->DyxlOrderWhere())
+            ->order('工单编号')
+            ->select();
+
+        $orderMap = [];
+        foreach ($orders as $row) {
+            $gdbh = trim((string)$row['工单编号']);
+            if ($gdbh === '') {
+                continue;
+            }
+            if (!isset($orderMap[$gdbh])) {
+                $orderMap[$gdbh] = [
+                    '年月' => trim((string)$row['年月']),
+                    '客户编号' => trim((string)$row['客户编号']),
+                    '客户名称' => trim((string)$row['客户名称']),
+                    '工单编号' => $gdbh,
+                    '成品名称' => trim((string)$row['成品名称']),
+                ];
+            } else {
+                if ($orderMap[$gdbh]['客户编号'] === '') {
+                    $orderMap[$gdbh]['客户编号'] = trim((string)$row['客户编号']);
+                }
+                if ($orderMap[$gdbh]['客户名称'] === '') {
+                    $orderMap[$gdbh]['客户名称'] = trim((string)$row['客户名称']);
+                }
+                if ($orderMap[$gdbh]['成品名称'] === '') {
+                    $orderMap[$gdbh]['成品名称'] = trim((string)$row['成品名称']);
+                }
+            }
+        }
+
+        if (empty($orderMap)) {
+            $this->success('成功', ['summary' => [], 'detail' => []]);
+        }
+
+        $gdbhs = array_keys($orderMap);
+        $categories = ['胶印', '凹印', '单凹', '喷码', '丝印', '烫金', '模切'];
+
+        // 2、工艺资料:工单 + 印件 + 工序
+        $crafts = \db('工单_工艺资料')
+            ->field([
+                "RTRIM(Gy0_gdbh) AS 工单编号",
+                "FLOOR(Gy0_yjno) AS 印件号",
+                "FLOOR(Gy0_gxh) AS 工序号",
+                "RTRIM(Gy0_gxmc) AS 工序名称",
+                "RTRIM(Gy0_sbbh) AS 设备编号",
+                "Gy0_计划接货数 AS 计划接货数",
+                "Gy0_ks AS 开数",
+                "Gy0_ls AS 印数",
+                "Gy0_小时产能 AS 小时产能",
+            ])
+            ->whereIn('Gy0_gdbh', $gdbhs)
+            ->order('工单编号, 印件号, 工序号')
+            ->select();
+
+        // 3、实际工时:设备_产量计酬 中同工单+印件+工序、设备运行工时不为0的记录
+        $actualRows = \db('设备_产量计酬')
+            ->field([
+                "RTRIM(sczl_gdbh) AS 工单编号",
+                "FLOOR(sczl_yjno) AS 印件号",
+                "FLOOR(sczl_gxh) AS 工序号",
+                "MAX(sczl_设备运行工时) AS 实际工时",
+            ])
+            ->whereIn('sczl_gdbh', $gdbhs)
+            ->where('sczl_设备运行工时', '<>', 0)
+            ->group('RTRIM(sczl_gdbh), FLOOR(sczl_yjno), FLOOR(sczl_gxh)')
+            ->select();
+
+        $actualMap = [];
+        foreach ($actualRows as $row) {
+            $actualMap[$this->DyxlKey($row['工单编号'], $row['印件号'], $row['工序号'])] = (float)$row['实际工时'];
+        }
+
+        $sumPlan = [];
+        $sumActual = [];
+        $detail = [];
+
+        foreach ($crafts as $craft) {
+            $gdbh = trim((string)$craft['工单编号']);
+            if (!isset($orderMap[$gdbh])) {
+                continue;
+            }
+            $category = $this->DyxlProcessCategory($craft['设备编号'], $craft['工序名称']);
+            if ($category === '') {
+                continue;
+            }
+
+            $yjno = (int)$craft['印件号'];
+            $gxh = (int)$craft['工序号'];
+            $plan = $this->DyxlPlanHours($craft);
+            $key = $this->DyxlKey($gdbh, $yjno, $gxh);
+            $actual = isset($actualMap[$key]) ? $actualMap[$key] : null;
+
+            if ($plan !== null) {
+                if (!isset($sumPlan[$gdbh][$category])) {
+                    $sumPlan[$gdbh][$category] = 0;
+                }
+                $sumPlan[$gdbh][$category] += $plan;
+            }
+            if ($actual !== null) {
+                if (!isset($sumActual[$gdbh][$category])) {
+                    $sumActual[$gdbh][$category] = 0;
+                }
+                $sumActual[$gdbh][$category] += $actual;
+            }
+
+            $detailRow = $orderMap[$gdbh];
+            $detailRow['印件及工序'] = str_pad($gxh, 2, '0', STR_PAD_LEFT) . '-' . trim((string)$craft['工序名称']);
+            foreach ($categories as $cat) {
+                $detailRow[$cat . '计划工时'] = '';
+                $detailRow[$cat . '实际工时'] = '';
+            }
+            if ($plan !== null) {
+                $detailRow[$category . '计划工时'] = $this->DyxlNumber($plan);
+            }
+            if ($actual !== null) {
+                $detailRow[$category . '实际工时'] = $this->DyxlNumber($actual);
+            }
+            $detail[] = $detailRow;
+        }
+
+        // 4、按工单汇总
+        $summary = [];
+        $totalPlan = array_fill_keys($categories, 0);
+        $totalActual = array_fill_keys($categories, 0);
+        $hasPlan = [];
+        $hasActual = [];
+
+        foreach ($orderMap as $gdbh => $info) {
+            $row = $info;
+            foreach ($categories as $cat) {
+                $plan = isset($sumPlan[$gdbh][$cat]) ? $sumPlan[$gdbh][$cat] : null;
+                $actual = isset($sumActual[$gdbh][$cat]) ? $sumActual[$gdbh][$cat] : null;
+                $row[$cat . '计划工时'] = $plan === null ? '' : $this->DyxlNumber($plan);
+                $row[$cat . '实际工时'] = $actual === null ? '' : $this->DyxlNumber($actual);
+                if ($plan !== null) {
+                    $totalPlan[$cat] += $plan;
+                    $hasPlan[$cat] = true;
+                }
+                if ($actual !== null) {
+                    $totalActual[$cat] += $actual;
+                    $hasActual[$cat] = true;
+                }
+            }
+            $summary[] = $row;
+        }
+
+        $totalRow = ['年月' => '合计:', '客户编号' => '', '客户名称' => '', '工单编号' => '', '成品名称' => ''];
+        foreach ($categories as $cat) {
+            $totalRow[$cat . '计划工时'] = !empty($hasPlan[$cat]) ? $this->DyxlNumber($totalPlan[$cat]) : '';
+            $totalRow[$cat . '实际工时'] = !empty($hasActual[$cat]) ? $this->DyxlNumber($totalActual[$cat]) : '';
+        }
+        $totalRow['isTotal'] = true;
+        if (!empty($summary)) {
+            $summary[] = $totalRow;
+        }
+
+        $this->success('成功', ['summary' => $summary, 'detail' => $detail]);
+    }
+
+    /**
+     * 打样工单条件:工单编号第3位(带Y前缀则第4位)为8
+     */
+    private function DyxlOrderWhere()
+    {
+        return "SUBSTRING(RTRIM(Gd_gdbh), IF(LEFT(RTRIM(Gd_gdbh), 1) = 'Y', 4, 3), 1) = '8'";
+    }
+
+    /**
+     * 按设备编号前缀判定工序类别
+     */
+    private function DyxlProcessCategory($sbbh, $gxmc)
+    {
+        $map = ['YJY' => '胶印', 'YWY' => '凹印', 'YDW' => '单凹', 'YPM' => '喷码', 'YSY' => '丝印', 'YTJ' => '烫金', 'YMQ' => '模切'];
+        $prefix = strtoupper(substr(trim((string)$sbbh), 0, 3));
+        if (isset($map[$prefix])) {
+            return $map[$prefix];
+        }
+
+        $name = trim((string)$gxmc);
+        foreach (['单凹' => '单凹', '凹印' => '凹印', '卷凹' => '凹印', '胶印' => '胶印', '喷码' => '喷码', '丝印' => '丝印', '烫金' => '烫金', '模切' => '模切'] as $keyword => $category) {
+            if (strpos($name, $keyword) !== false) {
+                return $category;
+            }
+        }
+        return '';
+    }
+
+    /**
+     * 计划工时 = 计划接货数 * 开数 * 印数 / 小时产能
+     */
+    private function DyxlPlanHours($craft)
+    {
+        $qty = (float)$craft['计划接货数'];
+        $ks = (float)$craft['开数'];
+        $ls = (float)$craft['印数'];
+        $capacity = (float)$craft['小时产能'];
+        if ($qty <= 0 || $ks <= 0 || $ls <= 0 || $capacity <= 0) {
+            return null;
+        }
+        return $qty * $ks * $ls / $capacity;
+    }
+
+    private function DyxlKey($gdbh, $yjno, $gxh)
+    {
+        return trim((string)$gdbh) . '|' . (int)$yjno . '|' . (int)$gxh;
+    }
+
+    private function DyxlNumber($value)
+    {
+        return number_format(round((float)$value, 2), 2, '.', '');
+    }
+
+    /**
+     * 年度手工检验统计 左侧菜单(年 -> 客户)
+     * 两阶段:先查手工检验取工单号 → 再工单_基本资料去重取客户
+     */
+    public function YearSgyjLeft()
+    {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+
+        $inspectRows = \db('db_手工检验')
+            ->field([
+                "DATE_FORMAT(sczl_rq, '%Y') AS 年份",
+                'UPPER(RTRIM(sczl_gdbh)) AS 工单编号',
+            ])
+            ->where('sczl_rq', '>=', '2000-01-01')
+            ->group('年份, 工单编号')
+            ->select();
+
+        if (empty($inspectRows)) {
+            $this->success('成功', []);
+        }
+
+        // 提取工单编号,查工单_基本资料并按 Gd_gdbh 去重
+        $gdbhs = array_values(array_unique(array_column($inspectRows, '工单编号')));
+        $orderMap = $this->YearSgyjOrderMap($gdbhs);
+
+        $years = [];
+        foreach ($inspectRows as $row) {
+            $year = trim((string)$row['年份']);
+            $gdbh = $row['工单编号'];
+            if ($year === '' || !isset($orderMap[$gdbh])) {
+                continue;
+            }
+            $info = $orderMap[$gdbh];
+            $code = $info['客户编号'];
+            $name = $info['客户名称'];
+            if ($code === '' && $name === '') {
+                continue;
+            }
+            if (!isset($years[$year])) {
+                $years[$year] = ['年份' => $year, '客户' => []];
+            }
+            $customerKey = $code !== '' ? $code : $name;
+            if (!isset($years[$year]['客户'][$customerKey])) {
+                $years[$year]['客户'][$customerKey] = [
+                    '客户编号' => $code,
+                    '客户名称' => $name,
+                ];
+            }
+        }
+        krsort($years);
+
+        $data = [];
+        foreach ($years as $year) {
+            ksort($year['客户']);
+            $year['客户'] = array_values($year['客户']);
+            $data[] = $year;
+        }
+
+        $this->success('成功', $data);
+    }
+
+    /**
+     * 年度手工检验统计 右侧数据
+     * 两阶段:先查手工检验 → 工单_基本资料按 Gd_gdbh 去重后 PHP 关联
+     */
+    public function YearSgyjList()
+    {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+
+        $param = $this->request->param();
+        $year = trim((string)(isset($param['year']) ? $param['year'] : ''));
+        if (!preg_match('/^\d{4}$/', $year)) {
+            $this->error('参数错误');
+        }
+        $customer = trim((string)(isset($param['customer']) ? $param['customer'] : ''));
+        $search = trim((string)(isset($param['search']) ? $param['search'] : ''));
+
+        $start = $year . '-01-01 00:00:00';
+        $end = ((int)$year + 1) . '-01-01 00:00:00';
+
+        // 1、手工检验数据(不 join)
+        $inspectRows = \db('db_手工检验')
+            ->field([
+                "DATE_FORMAT(sczl_rq, '%Y%m') AS 年月",
+                'UPPER(RTRIM(sczl_gdbh)) AS 工单编号',
+                'DATE_FORMAT(sczl_rq, \'%m\') AS 月份',
+                '(sczl_cl0+sczl_cl1+sczl_cl2+sczl_cl3+sczl_cl4+sczl_cl5+sczl_cl6+sczl_cl7+sczl_cl8+sczl_cl9+sczl_cl10+sczl_cl11+sczl_cl12) AS 总产量',
+            ])
+            ->where('sczl_rq', '>=', $start)
+            ->where('sczl_rq', '<', $end)
+            ->select();
+
+        if (empty($inspectRows)) {
+            $this->success('成功', ['summary' => [], 'detail' => []]);
+        }
+
+        // 2、工单编号 → 工单信息(去重)
+        $gdbhs = array_values(array_unique(array_filter(array_column($inspectRows, '工单编号'))));
+        $orderMap = $this->YearSgyjOrderMap($gdbhs);
+
+        // 3、组装完整行:合并工单信息到手工检验
+        $mergedRows = [];
+        foreach ($inspectRows as $row) {
+            $gdbh = $row['工单编号'];
+            if (!isset($orderMap[$gdbh])) {
+                continue;
+            }
+            $info = $orderMap[$gdbh];
+            $mergedRows[] = [
+                '年月' => trim((string)$row['年月']),
+                '工单编号' => $gdbh,
+                '月份' => (int)$row['月份'],
+                '总产量' => (float)$row['总产量'],
+                '产品编号' => $info['产品编号'],
+                '产品名称' => $info['产品名称'],
+                '客户编号' => $info['客户编号'],
+                '客户名称' => $info['客户名称'],
+                '产品类别' => $info['产品类别'],
+            ];
+        }
+
+        // 4、客户过滤 + 搜索过滤
+        if ($customer !== '') {
+            $mergedRows = array_values(array_filter($mergedRows, function ($r) use ($customer) {
+                return $r['客户编号'] === $customer;
+            }));
+        }
+        if ($search !== '') {
+            $mergedRows = array_values(array_filter($mergedRows, function ($r) use ($search) {
+                return strpos($r['产品编号'], $search) !== false || strpos($r['产品名称'], $search) !== false;
+            }));
+        }
+
+        if (empty($mergedRows)) {
+            $this->success('成功', ['summary' => [], 'detail' => []]);
+        }
+
+        // 5、summary:按 产品编号 聚合(产品编号为空时用产品名称兜底),按月份分月汇总
+        $products = [];
+        foreach ($mergedRows as $row) {
+            $code = $row['产品编号'];
+            if ($code === '') {
+                continue;
+            }
+            $m = $row['月份'];
+            if ($m < 1 || $m > 12) {
+                continue;
+            }
+            if (!isset($products[$code])) {
+                $products[$code] = [
+                    '产品编号' => $code,
+                    '产品名称' => $row['产品名称'],
+                    '产品类别' => $row['产品类别'],
+                    '客户编号' => $row['客户编号'],
+                    '客户名称' => $row['客户名称'],
+                    'monthly' => array_fill(1, 12, 0),
+                ];
+            }
+            $products[$code]['monthly'][$m] += $row['总产量'];
+        }
+
+        // 6、组装 summary 数组
+        $summary = [];
+        foreach ($products as $product) {
+            $totalAll = 0;
+            $months = [];
+            for ($m = 1; $m <= 12; $m++) {
+                $value = $product['monthly'][$m];
+                $totalAll += $value;
+                $months[str_pad($m, 2, '0', STR_PAD_LEFT) . '月'] = $value > 0 ? round($value, 2) : '';
+            }
+            $summary[] = array_merge([
+                '产品编号' => $product['产品编号'],
+                '产品名称' => $product['产品名称'],
+                '产品类别' => $product['产品类别'],
+                '每月合计' => round($totalAll, 2),
+            ], $months, [
+                '客户编号' => $product['客户编号'],
+                '客户名称' => $product['客户名称'],
+            ]);
+        }
+        usort($summary, function ($a, $b) {
+            return strcmp($a['产品编号'], $b['产品编号']);
+        });
+
+        // 7、summary 合计行:小盒合计、条盒合计
+        $totalRows = [];
+        foreach (['小盒', '条盒'] as $category) {
+            $exists = false;
+            $total = 0;
+            $sums = array_fill(1, 12, 0);
+            foreach ($summary as $row) {
+                if ($row['产品类别'] !== $category) {
+                    continue;
+                }
+                $exists = true;
+                $total += (float)$row['每月合计'];
+                for ($m = 1; $m <= 12; $m++) {
+                    $mk = str_pad($m, 2, '0', STR_PAD_LEFT) . '月';
+                    $sums[$m] += $row[$mk] === '' ? 0 : (float)$row[$mk];
+                }
+            }
+            if (!$exists) continue;
+            $totalRow = [
+                '产品编号' => $category . '合计',
+                '产品名称' => '',
+                '产品类别' => '',
+                '每月合计' => round($total, 2),
+                '合计类型' => true,
+                '客户编号' => '',
+                '客户名称' => '',
+            ];
+            for ($m = 1; $m <= 12; $m++) {
+                $totalRow[str_pad($m, 2, '0', STR_PAD_LEFT) . '月'] = round($sums[$m], 2);
+            }
+            $totalRows[] = $totalRow;
+        }
+        $summary = array_merge($summary, $totalRows);
+
+        // 8、detail:按 工单编号+年月 聚合
+        $detailMap = [];
+        foreach ($mergedRows as $row) {
+            $dKey = $row['工单编号'] . '|' . $row['年月'];
+            if (!isset($detailMap[$dKey])) {
+                $detailMap[$dKey] = [
+                    '年月' => $row['年月'],
+                    '工单编号' => $row['工单编号'],
+                    '产品编号' => $row['产品编号'],
+                    '产品名称' => $row['产品名称'],
+                    '产品类别' => $row['产品类别'],
+                    '总产量' => 0,
+                    '客户编号' => $row['客户编号'],
+                    '客户名称' => $row['客户名称'],
+                ];
+            }
+            $detailMap[$dKey]['总产量'] += $row['总产量'];
+        }
+        $detail = array_values($detailMap);
+        usort($detail, function ($a, $b) {
+            $c = strcmp($a['年月'], $b['年月']);
+            if ($c !== 0) return $c;
+            return strcmp($a['工单编号'], $b['工单编号']);
+        });
+        foreach ($detail as &$d) {
+            $d['总产量'] = round($d['总产量'], 2);
+        }
+        unset($d);
+
+        $this->success('成功', ['summary' => $summary, 'detail' => $detail]);
+    }
+
+    /**
+     * 工单_基本资料 按 Gd_gdbh 去重取一条
+     * 取第一个有客户代号且有成品编号的行;都没有时取第一条非空行
+     */
+    private function YearSgyjOrderMap(array $gdbhs)
+    {
+        if (empty($gdbhs)) {
+            return [];
+        }
+        $rows = \db('工单_基本资料')
+            ->field([
+                'UPPER(RTRIM(Gd_gdbh)) AS 工单编号',
+                'RTRIM(Gd_cpdh) AS 产品编号',
+                'RTRIM(成品名称) AS 产品名称',
+                'RTRIM(Gd_客户代号) AS 客户编号',
+                'RTRIM(Gd_客户名称) AS 客户名称',
+            ])
+            ->whereIn('Gd_gdbh', $gdbhs)
+            ->select();
+
+        $map = [];
+        foreach ($rows as $row) {
+            $gdbh = trim((string)$row['工单编号']);
+            if ($gdbh === '') continue;
+            $code = trim((string)$row['产品编号']);
+            $name = trim((string)$row['产品名称']);
+            $khdh = trim((string)$row['客户编号']);
+            $khmc = trim((string)$row['客户名称']);
+            $category = $name !== '' ? (strpos($name, '小盒') !== false ? '小盒' : '条盒') : '';
+
+            if (!isset($map[$gdbh])) {
+                // 第一次见到:如果有客户代号且有成品编号,直接用;否则先占坑
+                $map[$gdbh] = [
+                    '产品编号' => $code,
+                    '产品名称' => $name,
+                    '客户编号' => $khdh,
+                    '客户名称' => $khmc,
+                    '产品类别' => $category,
+                ];
+            } else {
+                // 已存在:如果现有记录缺客户,新记录有客户则覆盖;同理产品编号
+                if ($map[$gdbh]['客户编号'] === '' && $khdh !== '') {
+                    $map[$gdbh]['客户编号'] = $khdh;
+                    $map[$gdbh]['客户名称'] = $khmc;
+                }
+                if ($map[$gdbh]['产品编号'] === '' && $code !== '') {
+                    $map[$gdbh]['产品编号'] = $code;
+                    $map[$gdbh]['产品名称'] = $name;
+                    $map[$gdbh]['产品类别'] = $category;
+                }
+            }
+        }
+        return $map;
+    }
+
+    /**
+     * 设备周数据统计 左侧菜单(车间 -> 机台)
+     * 参考 facility/getTab,但去掉日期子节点
+     */
+    public function EqwdtLeft()
+    {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+
+        $department = \db('设备_基本资料')
+            ->distinct(true)
+            ->where('使用部门', '<>', '研发中心')
+            ->where('设备编组', '<>', '')
+            ->where('sys_sbID', '<>', '')
+            ->order('设备编组')
+            ->column('rtrim(使用部门) as 使用部门');
+
+        if (empty($department)) {
+            $this->success('成功', []);
+        }
+
+        $data = [];
+        foreach ($department as $dept) {
+            $machines = \db('设备_基本资料')
+                ->where('使用部门', $dept)
+                ->where('sys_sbID', '<>', '')
+                ->field('rtrim(设备编号) as 设备编号, rtrim(设备名称) as 设备名称')
+                ->order('设备编号')
+                ->select();
+
+            $machineNodes = [];
+            foreach ($machines as $m) {
+                $code = trim((string)$m['设备编号']);
+                if ($code === '') continue;
+                $machineNodes[] = [
+                    'label' => $code . '-->' . trim((string)$m['设备名称']),
+                    'key' => 'M' . $code,
+                    'machine' => $code,
+                ];
+            }
+            $data[] = [
+                'label' => $dept,
+                'key' => 'D' . $dept,
+                'children' => $machineNodes,
+            ];
+        }
+
+        $this->success('成功', $data);
+    }
+
+    /**
+     * 设备周数据统计 右侧汇总 + 明细
+     * 固定取数据库中最新日期往前 6 天(共 7 天)
+     * 参数: machine (可选机台编号)
+     */
+    public function EqwdtList()
+    {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+
+        $param = $this->request->param();
+        $machine = trim((string)(isset($param['machine']) ? $param['machine'] : ''));
+
+        // 以数据库最新日期为基准,取最近 7 天
+        $maxDate = \db('设备_产量计酬')->max('sczl_rq');
+        if (!$maxDate) {
+            $this->success('成功', ['summary' => [], 'detail' => [], 'range' => ['start' => '', 'end' => '']]);
+        }
+        $maxTs = strtotime($maxDate);
+        $end = date('Y-m-d', $maxTs);
+        $start = date('Y-m-d', $maxTs - 6 * 86400);
+        $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')
+            ->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 异常补时',
+            ])
+            ->where('s.sczl_rq', '>=', $startTime)
+            ->where('s.sczl_rq', '<', $endTime);
+
+        if ($machine !== '') {
+            $summaryQuery->where('s.sczl_jtbh', $machine);
+        }
+
+        $summary = $summaryQuery
+            ->group('机台编号, 设备名称, 使用部门, 生产工序, 设备编组')
+            ->order('机台编号')
+            ->select();
+
+        // 2、明细:工单级(按 机台编号 + 工单编号 + 日期 聚合)
+        $detailQuery = \db('设备_产量计酬')
+            ->alias('s')
+            ->join('设备_基本资料 b', 'RTRIM(b.设备编号) = RTRIM(s.sczl_jtbh)', 'LEFT')
+            ->join('工单_基本资料 g', 'RTRIM(g.Gd_gdbh) = RTRIM(s.sczl_gdbh)', 'LEFT')
+            ->field([
+                'DATE_FORMAT(s.sczl_rq, \'%Y-%m-%d\') AS 日期',
+                'RTRIM(s.sczl_jtbh) AS 机台编号',
+                'RTRIM(b.设备名称) AS 设备名称',
+                'RTRIM(s.sczl_gdbh) AS 工单编号',
+                'CONCAT(FLOOR(s.sczl_yjno), \'-\', RTRIM(s.sczl_gxmc)) AS 印件及工序',
+                'RTRIM(g.Gd_cpdh) AS 产品编号',
+                'RTRIM(g.成品名称) AS 成品名称',
+                'RTRIM(g.Gd_客户名称) 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_zcfp) AS 制程废品',
+                'SUM(s.sczl_zccp) AS 制程次品',
+            ])
+            ->where('s.sczl_rq', '>=', $startTime)
+            ->where('s.sczl_rq', '<', $endTime);
+
+        if ($machine !== '') {
+            $detailQuery->where('s.sczl_jtbh', $machine);
+        }
+
+        $detail = $detailQuery
+            ->group('日期, 机台编号, 设备名称, 工单编号, 印件及工序, 产品编号, 成品名称, 客户名称')
+            ->order('日期, 机台编号, 工单编号')
+            ->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];
+                $row[$k] = $v === 0 ? '' : round($v, 2);
+            }
+        }
+        unset($row);
+
+        $this->success('成功', [
+            'summary' => $summary,
+            'detail' => $detail,
+            'range' => ['start' => $start, 'end' => $end],
+        ]);
+    }
+
+    /**
+     * 完工工单生产周期统计 左侧菜单(年月 → 客户)
+     * 参考 order_super_loss/getTab
+     */
+    public function CopsTab()
+    {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+
+        $sql = "SELECT
+            DATE_FORMAT(a.接单日期, '%Y%m') AS date,
+            COUNT(DISTINCT a.Gd_gdbh) AS cnt,
+            RTRIM(a.Gd_客户代号) AS code,
+            RTRIM(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))
+        GROUP BY date, code, name
+        ORDER BY date DESC, code ASC";
+        $rows = Db::query($sql);
+
+        // 组装为 { date-total: [{code, name, total}] } 结构
+        $organized = [];
+        foreach ($rows as $r) {
+            $date = $r['date'];
+            if (!isset($organized[$date])) {
+                $organized[$date] = ['total_count' => 0, 'items' => []];
+            }
+            $organized[$date]['items'][] = [
+                'code' => $r['code'],
+                'name' => $r['name'],
+                'total' => intval($r['cnt']),
+            ];
+            $organized[$date]['total_count'] += intval($r['cnt']);
+        }
+
+        $data = [];
+        foreach ($organized as $date => $info) {
+            $key = $date . '-' . $info['total_count'];
+            foreach ($info['items'] as $it) {
+                $data[$key][] = $it;
+            }
+        }
+
+        $this->success('成功', $data);
+    }
+
+    /**
+     * 完工工单生产周期统计 右侧列表(纯 SQL 避免 TP5 Query 方法缺失)
+     * 参数: date (年月 YYYYMM), code (客户代号), search (关键字搜索),
+     *       page (页码, 默认1), limit (每页条数, 默认50), export (1=导出全量, 不分页)
+     */
+    public function CopsList()
+    {
+        if ($this->request->isGet() === false) {
+            $this->error('请求错误');
+        }
+
+        $param = $this->request->param();
+        $date = trim((string)(isset($param['date']) ? $param['date'] : ''));
+        $code = trim((string)(isset($param['code']) ? $param['code'] : ''));
+        $search = trim((string)(isset($param['search']) ? $param['search'] : ''));
+
+        $page = empty($param['page']) ? 1 : max(1, intval($param['page']));
+        $limit = empty($param['limit']) ? 50 : max(1, intval($param['limit']));
+        $isExport = !empty($param['export']);
+        // 导出全量时限制上限,避免一次性拉爆内存
+        if ($isExport) {
+            $page = 1;
+            $limit = 50000;
+        }
+        $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)";
+
+        if ($date !== '') {
+            $where[] = "DATE_FORMAT(a.接单日期, '%Y%m') = " . intval($date);
+        }
+        if ($code !== '') {
+            $escaped = str_replace("'", "''", $code);
+            $where[] = "UPPER(RTRIM(a.Gd_客户代号)) = UPPER(RTRIM('{$escaped}'))";
+        }
+        if ($search !== '') {
+            $escaped = str_replace("'", "''", $search);
+            $where[] = "(a.Gd_gdbh LIKE '%{$escaped}%' OR a.成品名称 LIKE '%{$escaped}%' OR a.Gd_cpdh LIKE '%{$escaped}%')";
+        }
+
+        $whereSql = implode(' AND ', $where);
+
+        // 公共 FROM 段(与 a 表 1:1 关联,可用于统计总数)
+        $fromSql = "FROM `工单_基本资料` a
+        LEFT JOIN `工单_印件资料` b
+            ON a.Gd_gdbh = b.Yj_Gdbh AND CAST(a.行号 AS UNSIGNED) = b.yj_Yjno
+        LEFT JOIN (
+            SELECT jjcp_gdbh, jjcp_yjno,
+                SUM(jjcp_sl) AS 入仓数量,
+                MIN(jjcp_sj) AS 检验日期,
+                MAX(jjcp_sj) AS 入仓完工日期
+            FROM `成品入仓`
+            GROUP BY jjcp_gdbh, jjcp_yjno
+        ) c
+            ON a.Gd_gdbh = c.jjcp_gdbh AND CAST(a.行号 AS UNSIGNED) = c.jjcp_yjno
+        WHERE {$whereSql}";
+
+        // 总数
+        $totalRow = Db::query("SELECT COUNT(*) AS total {$fromSql}");
+        $total = isset($totalRow[0]['total']) ? (int)$totalRow[0]['total'] : 0;
+
+        $sql = "SELECT
+            RTRIM(a.Gd_生产分类) AS 生产分类,
+            RTRIM(a.Gd_gdbh) AS 工单编号,
+            RTRIM(b.yj_Yjdh) AS 印件代号,
+            RTRIM(a.Gd_cpdh) AS 产品代号,
+            RTRIM(a.成品名称) AS 产品名称,
+            a.订单数量,
+            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(a.接单日期) AS 接单日期,
+            DATE(COALESCE(c.入仓完工日期, NULLIF(a.入仓日期, '1900-01-01 00:00:00'), a.工单完工日期)) AS 入仓完工日期,
+            RTRIM(a.Gd_客户代号) AS 客户代号,
+            RTRIM(a.Gd_客户名称) AS 客户名称,
+            RTRIM(a.销售订单号) AS 销售订单号
+        {$fromSql}
+        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['实际合格率'] = '';
+            }
+
+            foreach (['检验日期', '检验时间', '接单日期', '入仓完工日期'] as $k) {
+                if ($row[$k] === null || $row[$k] === '1900-01-01' || $row[$k] === '1900-01-01 00:00:00') {
+                    $row[$k] = '';
+                }
+            }
+        }
+        unset($row);
+
+        $this->success('成功', [
+            'list' => $list,
+            'total' => $total,
+            'page' => $page,
+            'limit' => $limit,
+        ]);
+    }
 }

+ 84 - 0
application/api/controller/Demoss.php

@@ -0,0 +1,84 @@
+<?php
+
+namespace app\api\controller;
+
+use app\common\controller\Api;
+use \think\Request;
+use \think\Db;
+class Demoss extends Api
+{
+    protected $noNeedLogin = ['*'];
+    protected $noNeedRight = ['*'];
+
+    public function index()
+    {
+        $this->success('13245645');
+    }
+
+    public function aaa()
+    {
+        $this->success('请求成功');
+    }
+
+    /**
+     * 墨色数审计结果批量查询
+     * 
+     * 用法:
+     *   GET  /api/demoss/batch?gdbhs=Y2680921,Y2680920
+     */
+    public function batch()
+    {
+        // 1. GET 请求校验(和现有接口风格一致)
+        if (!$this->request->isGet()) {
+            $this->error('请求方式错误');
+        }
+
+        // 2. 接收参数
+        $req = $this->request->param();
+        $gdbhsStr = isset($req['gdbhs']) ? trim($req['gdbhs']) : '';
+        if (empty($gdbhsStr)) {
+            $this->error('参数 gdbhs 不能为空');
+        }
+
+        // 3. 解析成数组
+        $gdbhList = array_filter(array_map('trim', explode(',', $gdbhsStr)));
+        if (empty($gdbhList)) {
+            $this->error('gdbhs 解析后为空');
+        }
+        $gdbhList = array_slice(array_unique($gdbhList), 0, 200);
+
+        // 4. 查询(用 db() 辅助函数,自动加表前缀)
+        //    前提:审计表已改名为 {prefix}audit_color_check
+        $rows = db('audit_color_check')
+            ->where('gdbh', 'in', $gdbhList)
+            ->field('gdbh,gxh,gxmc,colors_count,gy_ms,sczl_ms,error_field,is_valid,reason,suggestion,sczl_rq')
+            ->select();
+
+        if (!$rows) {
+            // 和现有风格一致:查询无数据不报错,返回空 map
+            $this->success('成功', []);
+        }
+
+        // 5. 组装成 map:key = "gdbh-gxh"
+        $resultMap = [];
+        foreach ($rows as $row) {
+            $key = $row['gdbh'] . '-' . $row['gxh'];
+            $resultMap[$key] = [
+                'gdbh'         => $row['gdbh'],
+                'gxh'          => $row['gxh'],
+                'gxmc'         => $row['gxmc'],
+                'colors_count' => (int)$row['colors_count'],
+                'gy_ms'        => (float)$row['gy_ms'],
+                'sczl_ms'      => (float)$row['sczl_ms'],
+                'error_field'  => $row['error_field'],
+                'is_valid'     => (int)$row['is_valid'],
+                'reason'       => $row['reason'],
+                'suggestion'   => $row['suggestion'],
+                'sczl_rq'      => $row['sczl_rq'],
+            ];
+        }
+
+        // 6. 返回
+        $this->success('成功', $resultMap);
+    }
+}

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

@@ -1475,7 +1475,7 @@ class Facility extends Api
             ->where('开工时间',$param['start'])
             ->where('设备编号',$param['machine'])
             ->where('sys_rq','>',$param['start'])
-            ->where('工单编号',$machineDetail['工单编号'])
+            // ->where('工单编号',$machineDetail['工单编号'])
             ->field('rtrim(类别) as 类别,提交时间')
             ->select();
 
@@ -3164,9 +3164,9 @@ class Facility extends Api
             $this->error('请求错误');
         }
         $param = $this->request->param();
-        $where = [
-            '类别' => '现场巡查记录'
-        ];
+        // $where = [
+        //     '类别' => '现场巡查记录'
+        // ];
         if (isset($param['machine'])){
             $where['设备编号'] = $param['machine'];
         }
@@ -3185,6 +3185,7 @@ class Facility extends Api
             }
             array_push($result[$value['设备编号']],$date);
         }
+        ksort($result);
         $this->success('成功',$result);
     }
 
@@ -3202,7 +3203,7 @@ class Facility extends Api
             $this->error('参数错误');
         }
         $where = [
-            '类别' => '现场巡查记录',
+            // '类别' => '现场巡查记录',
             '设备编号' => $param['machine'],
             '提交时间' => ['like',$param['date'].'%'],
         ];