unknown преди 1 месец
родител
ревизия
5c8b2504f1
променени са 1 файла, в които са добавени 84 реда и са изтрити 84 реда
  1. 84 84
      application/service/UnifiedCostCalculationService.php

+ 84 - 84
application/service/UnifiedCostCalculationService.php

@@ -95,7 +95,7 @@ class UnifiedCostCalculationService
     {
         Db::startTrans();
         try {
-   
+
 
             if (!isset($param['month'])) {
                 throw new Exception("缺少必要参数: month");
@@ -113,7 +113,7 @@ class UnifiedCostCalculationService
 
             // 2. 执行五项计算
             $this->calculateDirectLabor($param);
-            Log::info("直接人工计算完成", ['记录数' => is_countable($this->monthlyCostDetails) ? count($this->monthlyCostDetails) : 0]);
+//            Log::info("直接人工计算完成", ['记录数' => is_countable($this->monthlyCostDetails) ? count($this->monthlyCostDetails) : 0]);
 
             $this->calculateDirectUtilities($param);
             $this->calculateIndirectMaterials($month);
@@ -138,13 +138,13 @@ class UnifiedCostCalculationService
                 error_log("堆栈跟踪: " . $t->getTraceAsString());
 
                 // 尝试记录到系统日志
-                if (class_exists('think\Log')) {
-                    Log::error("成本核算失败(直接记录)", [
-                        'message' => $t->getMessage(),
-                        'file' => $t->getFile(),
-                        'line' => $t->getLine()
-                    ]);
-                }
+//                if (class_exists('think\Log')) {
+//                    Log::error("成本核算失败(直接记录)", [
+//                        'message' => $t->getMessage(),
+//                        'file' => $t->getFile(),
+//                        'line' => $t->getLine()
+//                    ]);
+//                }
             } catch (\Throwable $logError) {
                 // 忽略日志记录错误
             }
@@ -170,7 +170,7 @@ class UnifiedCostCalculationService
         $this->allocationFactors = [];
 
         // 记录清空操作
-        Log::info("清空旧数据", ['month' => $month]);
+//        Log::info("清空旧数据", ['month' => $month]);
     }
 
     /**
@@ -198,13 +198,13 @@ class UnifiedCostCalculationService
                 $list = $list->toArray();
             }
 
-            Log::info("直接人工查询结果数: " . count($list));
+//            Log::info("直接人工查询结果数: " . count($list));
 
             foreach ($list as $item) {
                 // 确保 $item 是数组
                 $itemArray = is_object($item) ? (array)$item : $item;
                 if (!is_array($itemArray)) {
-                    Log::warning("直接人工数据项格式不正确: " . gettype($item));
+//                    Log::warning("直接人工数据项格式不正确: " . gettype($item));
                     continue;
                 }
 
@@ -212,7 +212,7 @@ class UnifiedCostCalculationService
             }
 
         } catch (\Exception $e) {
-            Log::error("计算直接人工失败: " . $e->getMessage());
+//            Log::error("计算直接人工失败: " . $e->getMessage());
             throw new Exception("直接人工计算失败: " . $e->getMessage());
         }
     }
@@ -306,7 +306,7 @@ class UnifiedCostCalculationService
 
         $utilityData = $this->fetchDirectUtilities($month);
         if (empty($utilityData)) {
-            Log::info("{$month}月份未找到直接水电费用数据");
+//            Log::info("{$month}月份未找到直接水电费用数据");
             return;
         }
 
@@ -398,7 +398,7 @@ class UnifiedCostCalculationService
                 // 确保 $detail 是数组
                 $detailArray = is_object($detail) ? (array)$detail : $detail;
                 if (!is_array($detailArray)) {
-                    Log::warning("成本明细数据格式不正确: " . gettype($detail));
+//                    Log::warning("成本明细数据格式不正确: " . gettype($detail));
                     continue;
                 }
 
@@ -416,12 +416,12 @@ class UnifiedCostCalculationService
                     ];
                 }
             } catch (\Exception $e) {
-                Log::error("处理机台工作小时数时出错: " . $e->getMessage());
+//                Log::error("处理机台工作小时数时出错: " . $e->getMessage());
                 continue;
             }
         }
 
-        Log::info("从月度成本明细数据中获取机台运行时间,记录数: " . count($workHours));
+//        Log::info("从月度成本明细数据中获取机台运行时间,记录数: " . count($workHours));
 
         return $workHours;
     }
@@ -462,7 +462,7 @@ class UnifiedCostCalculationService
                 // 确保 $workOrder 是数组
                 $orderArray = is_object($workOrder) ? (array)$workOrder : $workOrder;
                 if (!is_array($orderArray)) {
-                    Log::warning("工单小时数据格式不正确: " . gettype($workOrder));
+//                    Log::warning("工单小时数据格式不正确: " . gettype($workOrder));
                     $skippedCount++;
                     continue;
                 }
@@ -471,25 +471,25 @@ class UnifiedCostCalculationService
                 $hours = floatval($orderArray['占用机时'] ?? 0);
 
                 if (empty($machineCode)) {
-                    Log::debug("工单缺少机器编号: " . json_encode($orderArray));
+//                    Log::debug("工单缺少机器编号: " . json_encode($orderArray));
                     $skippedCount++;
                     continue;
                 }
 
                 if (!isset($machineUtilities[$machineCode])) {
-                    Log::debug("机器 {$machineCode} 没有水电费用数据");
+//                    Log::debug("机器 {$machineCode} 没有水电费用数据");
                     $skippedCount++;
                     continue;
                 }
 
                 if ($machineUtilities[$machineCode]['总费用'] <= 0) {
-                    Log::debug("机器 {$machineCode} 水电费用为0");
+//                    Log::debug("机器 {$machineCode} 水电费用为0");
                     $skippedCount++;
                     continue;
                 }
 
                 if (!isset($machineTotalHours[$machineCode]) || $machineTotalHours[$machineCode] <= 0) {
-                    Log::warning("机器 {$machineCode} 总运行时间为0,无法分摊");
+//                    Log::warning("机器 {$machineCode} 总运行时间为0,无法分摊");
                     $skippedCount++;
                     continue;
                 }
@@ -515,13 +515,13 @@ class UnifiedCostCalculationService
                 $processedCount++;
 
             } catch (\Exception $e) {
-                Log::error("分摊水电到工单时出错: " . $e->getMessage());
+//                Log::error("分摊水电到工单时出错: " . $e->getMessage());
                 $skippedCount++;
                 continue;
             }
         }
 
-        Log::info("分摊水电处理完成,成功: {$processedCount}, 跳过: {$skippedCount}, 总计: " . count($workOrderHours));
+//        Log::info("分摊水电处理完成,成功: {$processedCount}, 跳过: {$skippedCount}, 总计: " . count($workOrderHours));
 
         return $allocationResults;
     }
@@ -534,7 +534,7 @@ class UnifiedCostCalculationService
     {
         // 记录传入参数的类型和内容(用于调试)
         $type = gettype($workOrder);
-        Log::debug("getWorkOrderUniqueKey 接收参数类型: {$type}");
+//        Log::debug("getWorkOrderUniqueKey 接收参数类型: {$type}");
 
         // 如果是对象,转换为数组
         if (is_object($workOrder)) {
@@ -542,15 +542,15 @@ class UnifiedCostCalculationService
         }
 
         // 确保是数组
-        if (!is_array($workOrder)) {
-            Log::error("getWorkOrderUniqueKey 参数不是数组: {$type}, 值: " . print_r($workOrder, true));
-            return 'invalid-' . uniqid();
-        }
+//        if (!is_array($workOrder)) {
+//            Log::error("getWorkOrderUniqueKey 参数不是数组: {$type}, 值: " . print_r($workOrder, true));
+//            return 'invalid-' . uniqid();
+//        }
 
         // 调试:记录数组内容
-        if (count($workOrder) < 4) {
-            Log::debug("getWorkOrderUniqueKey 数组内容: " . json_encode($workOrder));
-        }
+//        if (count($workOrder) < 4) {
+//            Log::debug("getWorkOrderUniqueKey 数组内容: " . json_encode($workOrder));
+//        }
 
         // 安全地获取所有可能键名
         $gdbh = '';
@@ -584,12 +584,12 @@ class UnifiedCostCalculationService
         }
 
         // 验证所有字段都不为空
-        if (empty($gdbh) || empty($yjno) || empty($gxh) || empty($jtbh)) {
-            Log::warning("工单唯一键字段不完整: gdbh={$gdbh}, yjno={$yjno}, gxh={$gxh}, jtbh={$jtbh}");
-        }
+//        if (empty($gdbh) || empty($yjno) || empty($gxh) || empty($jtbh)) {
+//            Log::warning("工单唯一键字段不完整: gdbh={$gdbh}, yjno={$yjno}, gxh={$gxh}, jtbh={$jtbh}");
+//        }
 
         $key = sprintf('%s-%s-%s-%s', $gdbh, $yjno, $gxh, $jtbh);
-        Log::debug("生成的唯一键: {$key}");
+//        Log::debug("生成的唯一键: {$key}");
 
         return $key;
     }
@@ -600,7 +600,7 @@ class UnifiedCostCalculationService
     protected function updateDirectUtilitiesToCostDetails(array $allocationResults): void
     {
         if (empty($allocationResults) || empty($this->monthlyCostDetails)) {
-            Log::warning("水电费分配结果或成本明细数据为空,无法更新");
+//            Log::warning("水电费分配结果或成本明细数据为空,无法更新");
             return;
         }
 
@@ -624,17 +624,17 @@ class UnifiedCostCalculationService
                     $notFoundCount++;
                 }
             } catch (\Exception $e) {
-                Log::error("更新直接水电费时出错: " . $e->getMessage());
+//                Log::error("更新直接水电费时出错: " . $e->getMessage());
                 continue;
             }
         }
 
-        Log::info("已更新直接水电费的工单数量: {$updatedCount}, 未找到的工单数: {$notFoundCount}, 分配总金额: {$totalAllocatedAmount}");
+//        Log::info("已更新直接水电费的工单数量: {$updatedCount}, 未找到的工单数: {$notFoundCount}, 分配总金额: {$totalAllocatedAmount}");
 
         // 如果有大量未找到的工单,记录详细信息
-        if ($notFoundCount > 0 && $notFoundCount > $updatedCount) {
-            Log::warning("有大量工单未匹配到水电费分配结果,可能键名不匹配");
-        }
+//        if ($notFoundCount > 0 && $notFoundCount > $updatedCount) {
+//            Log::warning("有大量工单未匹配到水电费分配结果,可能键名不匹配");
+//        }
     }
 
     /**
@@ -858,13 +858,13 @@ class UnifiedCostCalculationService
 
             $utilityData = $this->fetchApportionedUtilities($month);
             if (empty($utilityData)) {
-                Log::info("{$month}月份未找到分摊水电数据");
+//                Log::info("{$month}月份未找到分摊水电数据");
                 return;
             }
 
             // 记录原始科目名称用于调试
             $originalSubjects = array_unique(array_column($utilityData, '科目名称'));
-            Log::info("原始科目名称: " . implode(', ', $originalSubjects));
+//            Log::info("原始科目名称: " . implode(', ', $originalSubjects));
 
             $machineAllocations = $this->calculateMachineAllocations($utilityData);
 
@@ -873,7 +873,7 @@ class UnifiedCostCalculationService
                 $this->allocateApportionedUtilities($machineAllocations);
             }
         } catch (\Exception $e) {
-            Log::error("计算分摊水电时出错: " . $e->getMessage());
+//            Log::error("计算分摊水电时出错: " . $e->getMessage());
             throw new Exception("分摊水电计算失败: " . $e->getMessage());
         }
     }
@@ -908,7 +908,7 @@ class UnifiedCostCalculationService
 
                 $this->allocateBySubject($allocations, $subject, $amount, $machineHours);
             } catch (\Exception $e) {
-                Log::error("计算机台分摊金额时出错: " . $e->getMessage());
+//                Log::error("计算机台分摊金额时出错: " . $e->getMessage());
                 continue;
             }
         }
@@ -954,7 +954,7 @@ class UnifiedCostCalculationService
                 $this->allocateGlobally($allocations, $subject, $amount, $machineHours);
             }
         } catch (\Exception $e) {
-            Log::error("按科目分摊时出错 (科目: {$subject}): " . $e->getMessage());
+//            Log::error("按科目分摊时出错 (科目: {$subject}): " . $e->getMessage());
         }
     }
 
@@ -1072,7 +1072,7 @@ class UnifiedCostCalculationService
     ): void {
         $totalHours = array_sum($machineHours);
         if ($totalHours <= 0) {
-            Log::warning("全局分摊失败:总机时为0");
+//            Log::warning("全局分摊失败:总机时为0");
             return;
         }
 
@@ -1080,7 +1080,7 @@ class UnifiedCostCalculationService
             try {
                 // 确保 $machine 是有效的字符串键名
                 if (!is_string($machine) && !is_numeric($machine)) {
-                    Log::warning("无效的机器键名: " . print_r($machine, true));
+//                    Log::warning("无效的机器键名: " . print_r($machine, true));
                     continue;
                 }
 
@@ -1099,7 +1099,7 @@ class UnifiedCostCalculationService
                     ($allocations[$machine][$subject] ?? 0) + $machineAmount;
 
             } catch (\Exception $e) {
-                Log::error("全局分摊到机器 {$machine} 时出错: " . $e->getMessage());
+//                Log::error("全局分摊到机器 {$machine} 时出错: " . $e->getMessage());
                 continue;
             }
         }
@@ -1167,13 +1167,13 @@ class UnifiedCostCalculationService
         // 尝试部分匹配
         foreach (self::SUBJECT_TO_FIELD_MAP as $keyword => $mappedField) {
             if (strpos($subject, $keyword) !== false) {
-                Log::debug("科目名称部分匹配: {$subject} => {$mappedField} (关键词: {$keyword})");
+//                Log::debug("科目名称部分匹配: {$subject} => {$mappedField} (关键词: {$keyword})");
                 return $mappedField;
             }
         }
 
         // 如果都不匹配,使用默认映射
-        Log::warning("未识别的科目名称: {$subject}, 将映射到 '分摊水电'");
+//        Log::warning("未识别的科目名称: {$subject}, 将映射到 '分摊水电'");
         return '分摊水电';
     }
 
@@ -1196,13 +1196,13 @@ class UnifiedCostCalculationService
 
         foreach ($allocations as $machine => $subjects) {
             if (!is_string($machine) && !is_numeric($machine)) {
-                Log::warning("无效的机台标识: " . print_r($machine, true));
+//                Log::warning("无效的机台标识: " . print_r($machine, true));
                 continue;
             }
 
             foreach ($subjects as $subject => $amount) {
                 if (!is_string($subject)) {
-                    Log::warning("无效的科目名称: " . print_r($subject, true));
+//                    Log::warning("无效的科目名称: " . print_r($subject, true));
                     continue;
                 }
 
@@ -1243,7 +1243,7 @@ class UnifiedCostCalculationService
             foreach ($machineRates[$machine] as $subject => $rate) {
                 $field = $this->getUtilityFieldName($subject);
                 if (!isset($detail[$field])) {
-                    Log::warning("数据库字段不存在: {$field},跳过该分摊");
+//                    Log::warning("数据库字段不存在: {$field},跳过该分摊");
                     continue;
                 }
                 $detail[$field] = round($hours * $rate, 2);
@@ -1292,7 +1292,7 @@ class UnifiedCostCalculationService
         }
 
         // 默认映射到 '分摊水电'
-        Log::warning("未知的科目字段: {$subject}, 映射到 '分摊水电'");
+//        Log::warning("未知的科目字段: {$subject}, 映射到 '分摊水电'");
         return '分摊水电';
     }
 
@@ -1327,13 +1327,13 @@ class UnifiedCostCalculationService
     {
         try {
             if (!is_array($this->monthlyCostDetails)) {
-                Log::error("monthlyCostDetails 不是数组: " . gettype($this->monthlyCostDetails));
+//                Log::error("monthlyCostDetails 不是数组: " . gettype($this->monthlyCostDetails));
                 $this->monthlyCostDetails = [];
                 return;
             }
 
             if (empty($this->monthlyCostDetails)) {
-                Log::warning("月度成本明细数据为空");
+//                Log::warning("月度成本明细数据为空");
                 return;
             }
 
@@ -1341,18 +1341,18 @@ class UnifiedCostCalculationService
 
             $columns = Db::query("DESCRIBE `{$tableName}`");
             if (empty($columns)) {
-                Log::error("无法获取表结构: {$tableName}");
+//                Log::error("无法获取表结构: {$tableName}");
                 return;
             }
 
             $columnNames = array_column($columns, 'Field');
-            Log::info("表{$tableName}结构字段数: " . count($columnNames));
+//            Log::info("表{$tableName}结构字段数: " . count($columnNames));
 
             // 验证并修复每条记录
             foreach ($this->monthlyCostDetails as $index => &$row) {
                 // 确保行是数组
                 if (!is_array($row)) {
-                    Log::warning("第{$index}行不是数组: " . gettype($row));
+//                    Log::warning("第{$index}行不是数组: " . gettype($row));
                     $row = [];
                     continue;
                 }
@@ -1362,14 +1362,14 @@ class UnifiedCostCalculationService
                 $columnCount = count($columnNames);
 
                 if ($rowCount !== $columnCount) {
-                    Log::warning("第" . ($index + 1) . "行字段数不匹配: 数据{$rowCount}个,表{$columnCount}个");
+//                    Log::warning("第" . ($index + 1) . "行字段数不匹配: 数据{$rowCount}个,表{$columnCount}个");
                     $this->fixRowData($row, $columnNames, $index);
                 }
 
                 // 确保所有键名都是字符串
                 foreach ($row as $key => $value) {
                     if (!is_string($key) && !is_int($key)) {
-                        Log::warning("发现非法键名类型 (行 {$index}): " . gettype($key));
+//                        Log::warning("发现非法键名类型 (行 {$index}): " . gettype($key));
                         // 移除非法键名
                         unset($row[$key]);
                         // 如果有值,尝试保存
@@ -1380,10 +1380,10 @@ class UnifiedCostCalculationService
                 }
             }
 
-            Log::info("数据结构验证完成,总记录数: " . count($this->monthlyCostDetails));
+//            Log::info("数据结构验证完成,总记录数: " . count($this->monthlyCostDetails));
 
         } catch (\Throwable $t) {
-            Log::error("验证数据结构时出错: " . $t->getMessage());
+//            Log::error("验证数据结构时出错: " . $t->getMessage());
             // 不抛出异常,继续执行
         }
     }
@@ -1417,7 +1417,7 @@ class UnifiedCostCalculationService
         }
 
         $this->monthlyCostDetails[$index] = $fixedRow;
-        Log::info("已修复第" . ($index + 1) . "行数据");
+//        Log::info("已修复第" . ($index + 1) . "行数据");
     }
 
 
@@ -1453,7 +1453,7 @@ class UnifiedCostCalculationService
     protected function insertBatch(array $batch, string $tableName, int $startIndex): void
     {
         if (empty($batch)) {
-            Log::warning("批次数据为空,跳过插入");
+//            Log::warning("批次数据为空,跳过插入");
             return;
         }
 
@@ -1463,7 +1463,7 @@ class UnifiedCostCalculationService
         // 验证字段名不包含特殊字符
         foreach ($fields as $field) {
             if (preg_match('/[#@$%^&*()+\-=\[\]{}|;:"<>,.?\/]/', $field)) {
-                Log::error("字段名包含特殊字符: {$field}");
+//                Log::error("字段名包含特殊字符: {$field}");
                 throw new Exception("字段名 '{$field}' 包含非法字符");
             }
         }
@@ -1486,23 +1486,23 @@ class UnifiedCostCalculationService
             $values[] = '(' . implode(',', $rowValues) . ')';
 
             // 记录第一行数据用于调试
-            if ($rowIndex === 0 && $startIndex === 0) {
-                Log::debug("第一行数据字段: " . implode(', ', $fields));
-                Log::debug("第一行数据值: " . implode(', ', $rowValues));
-            }
+//            if ($rowIndex === 0 && $startIndex === 0) {
+//                Log::debug("第一行数据字段: " . implode(', ', $fields));
+//                Log::debug("第一行数据值: " . implode(', ', $rowValues));
+//            }
         }
 
         $sql = "INSERT INTO `{$tableName}` ({$fieldStr}) VALUES " . implode(',', $values);
 
         // 记录SQL语句(前200个字符)
-        Log::debug("SQL语句: " . substr($sql, 0, 200) . "...");
+//        Log::debug("SQL语句: " . substr($sql, 0, 200) . "...");
 
         try {
             $result = Db::execute($sql);
-            Log::info("成功插入批次 " . (($startIndex / self::BATCH_SIZE) + 1) . ", 影响行数: " . $result);
+//            Log::info("成功插入批次 " . (($startIndex / self::BATCH_SIZE) + 1) . ", 影响行数: " . $result);
         } catch (\Exception $e) {
-            Log::error("插入批次失败: " . $e->getMessage());
-            Log::error("失败SQL: " . $sql);
+//            Log::error("插入批次失败: " . $e->getMessage());
+//            Log::error("失败SQL: " . $sql);
             throw $e;
         }
     }
@@ -1547,11 +1547,11 @@ class UnifiedCostCalculationService
                 $logData['first_record_type'] = gettype($firstRecord);
             }
 
-            Log::info("成本核算完成", $logData);
+//            Log::info("成本核算完成", $logData);
 
         } catch (\Throwable $t) {
             // 如果日志记录失败,至少输出到标准错误
-            error_log("成本核算完成(日志记录失败): " . $t->getMessage());
+//            error_log("成本核算完成(日志记录失败): " . $t->getMessage());
         }
     }
 
@@ -1600,11 +1600,11 @@ class UnifiedCostCalculationService
                 '分摊系数数' => is_countable($this->allocationFactors) ? count($this->allocationFactors) : 'N/A',
             ];
 
-            Log::error("统一成本核算失败详情", $errorDetails);
+//            Log::error("统一成本核算失败详情", $errorDetails);
         } catch (\Throwable $logError) {
             // 如果日志记录也失败,至少输出到标准错误
-            error_log("无法记录错误日志: " . $logError->getMessage());
-            error_log("原始错误: " . $t->getMessage());
+//            error_log("无法记录错误日志: " . $logError->getMessage());
+//            error_log("原始错误: " . $t->getMessage());
         }
     }
 
@@ -1629,9 +1629,9 @@ class UnifiedCostCalculationService
         foreach ($row as $key => $value) {
             // 移除字段名中的特殊字符,只保留字母、数字、下划线和中文字符
             $cleanKey = preg_replace('/[^\w\x{4e00}-\x{9fa5}]/u', '', $key);
-            if ($cleanKey !== $key) {
-                Log::debug("清理字段名: {$key} => {$cleanKey}");
-            }
+//            if ($cleanKey !== $key) {
+//                Log::debug("清理字段名: {$key} => {$cleanKey}");
+//            }
             $sanitized[$cleanKey] = $value;
         }
         $row = $sanitized;