فهرست منبع

fleat: add stats

igb 1 هفته پیش
والد
کامیت
ac30fbc481
5فایلهای تغییر یافته به همراه2513 افزوده شده و 0 حذف شده
  1. 732 0
      customer_composition_stats.php
  2. 726 0
      inquiry_conversion_stats.php
  3. 513 0
      monthly_deal_stats.php
  4. 4 0
      panel.php
  5. 538 0
      region_performance_stats.php

+ 732 - 0
customer_composition_stats.php

@@ -0,0 +1,732 @@
+<?php
+/**
+ * 每月业绩客户构成统计分析
+ */
+require_once 'conn.php';
+require_once 'statistics_utils.php';
+require_once 'statistics_customers.php';
+require_once 'statistics_sales.php';
+// 检查登录状态
+if (!isset($_SESSION['employee_id'])) {
+    checkLogin();
+}
+
+function formatCurrency($value) {
+    return '¥' . number_format($value ?? 0, 2);
+}
+
+function formatPercentage($value, $total) {
+    if ($total == 0) return '0%';
+    return round(($value / $total) * 100, 2) . '%';
+}
+
+// 获取当前登录用户信息
+$current_employee_id = $_SESSION['employee_id'];
+$current_permission_role = 0;
+
+// 获取当前用户权限角色
+$current_employee_id = intval($current_employee_id); // 确保是整数
+$query = "SELECT em_permission_role_id FROM employee WHERE id = $current_employee_id";
+$result = $conn->query($query);
+if ($result && $row = $result->fetch_assoc()) {
+    $current_permission_role = $row['em_permission_role_id'];
+}
+
+// 检查是否为导出请求
+$is_export = isset($_GET['export']) && $_GET['export'] == 'excel';
+
+// 获取日期范围参数
+$date_params = getDateRangeParams();
+$start_date = $date_params['start_date_sql'];
+$end_date = $date_params['end_date_sql'];
+$date_range = $date_params['date_range'];
+$period = $date_params['period'];
+
+// 如果不是导出操作,则包含页面头部
+if (!$is_export) {
+    include('statistics_header.php');
+}
+
+/**
+ * 获取业务员业绩的客户构成
+ */
+function getCustomerCompositionStats($conn, $start_date, $end_date, $employee_filter = null) {
+    // 查询业务员的新客户业绩(客户编码以0开头的)
+    $new_customer_sql = "SELECT 
+                e.id AS employee_id,
+                e.em_user AS employee_name,
+                COUNT(DISTINCT c.id) AS customer_count,
+                SUM(o.total_amount) AS total_amount
+            FROM orders o
+            JOIN customer c ON o.customer_id = c.id
+            JOIN employee e ON c.cs_belong = e.id
+            WHERE o.order_date BETWEEN '$start_date' AND '$end_date'
+            AND c.cs_deal = 3
+            AND c.cs_code LIKE '%.0%'";
+    
+    // 查询业务员的老客户业绩(客户编码以3开头且不包含斜杠的)
+    $old_customer_sql = "SELECT 
+                e.id AS employee_id,
+                e.em_user AS employee_name,
+                COUNT(DISTINCT c.id) AS customer_count,
+                SUM(o.total_amount) AS total_amount
+            FROM orders o
+            JOIN customer c ON o.customer_id = c.id
+            JOIN employee e ON c.cs_belong = e.id
+            WHERE o.order_date BETWEEN '$start_date' AND '$end_date'
+            AND c.cs_deal = 3
+            AND c.cs_code LIKE '%.3%'
+            AND c.cs_code NOT LIKE '%/%'";
+    
+    // 查询业务员的分配客户业绩(客户编码包含斜杠的)
+    $assigned_customer_sql = "SELECT 
+                e.id AS employee_id,
+                e.em_user AS employee_name,
+                COUNT(DISTINCT c.id) AS customer_count,
+                SUM(o.total_amount) AS total_amount
+            FROM orders o
+            JOIN customer c ON o.customer_id = c.id
+            JOIN employee e ON c.cs_belong = e.id
+            WHERE o.order_date BETWEEN '$start_date' AND '$end_date'
+            AND c.cs_deal = 3
+            AND c.cs_code LIKE '%/%'";
+    
+    // 查询业务员的总业绩
+    $total_sql = "SELECT 
+                e.id AS employee_id,
+                e.em_user AS employee_name,
+                COUNT(DISTINCT c.id) AS customer_count,
+                SUM(o.total_amount) AS total_amount
+            FROM orders o
+            JOIN customer c ON o.customer_id = c.id
+            JOIN employee e ON c.cs_belong = e.id
+            WHERE o.order_date BETWEEN '$start_date' AND '$end_date'
+            AND c.cs_deal = 3";
+    
+    // 根据员工过滤条件添加WHERE子句
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (!empty($employee_filter)) {
+                $employee_ids = implode(',', array_map('intval', $employee_filter));
+                $new_customer_sql .= " AND c.cs_belong IN ($employee_ids)";
+                $old_customer_sql .= " AND c.cs_belong IN ($employee_ids)";
+                $assigned_customer_sql .= " AND c.cs_belong IN ($employee_ids)";
+                $total_sql .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $employee_id = intval($employee_filter);
+            $new_customer_sql .= " AND c.cs_belong = $employee_id";
+            $old_customer_sql .= " AND c.cs_belong = $employee_id";
+            $assigned_customer_sql .= " AND c.cs_belong = $employee_id";
+            $total_sql .= " AND c.cs_belong = $employee_id";
+        }
+    }
+    
+    $new_customer_sql .= " GROUP BY e.id ORDER BY total_amount DESC";
+    $old_customer_sql .= " GROUP BY e.id ORDER BY total_amount DESC";
+    $assigned_customer_sql .= " GROUP BY e.id ORDER BY total_amount DESC";
+    $total_sql .= " GROUP BY e.id ORDER BY total_amount DESC";
+    
+    $new_result = $conn->query($new_customer_sql);
+    $old_result = $conn->query($old_customer_sql);
+    $assigned_result = $conn->query($assigned_customer_sql);
+    $total_result = $conn->query($total_sql);
+    
+    $new_data = [];
+    $old_data = [];
+    $assigned_data = [];
+    $total_data = [];
+    
+    if ($new_result) {
+        while ($row = $new_result->fetch_assoc()) {
+            $new_data[$row['employee_id']] = $row;
+        }
+    }
+    
+    if ($old_result) {
+        while ($row = $old_result->fetch_assoc()) {
+            $old_data[$row['employee_id']] = $row;
+        }
+    }
+    
+    if ($assigned_result) {
+        while ($row = $assigned_result->fetch_assoc()) {
+            $assigned_data[$row['employee_id']] = $row;
+        }
+    }
+    
+    if ($total_result) {
+        while ($row = $total_result->fetch_assoc()) {
+            $total_data[$row['employee_id']] = $row;
+        }
+    }
+    
+    // 合并数据
+    $combined_data = [];
+    
+    foreach ($total_data as $employee_id => $total) {
+        $combined_data[$employee_id] = [
+            'employee_id' => $employee_id,
+            'employee_name' => $total['employee_name'],
+            'total_customer_count' => $total['customer_count'],
+            'total_amount' => $total['total_amount'],
+            'new_customer_count' => $new_data[$employee_id]['customer_count'] ?? 0,
+            'new_customer_amount' => $new_data[$employee_id]['total_amount'] ?? 0,
+            'old_customer_count' => $old_data[$employee_id]['customer_count'] ?? 0,
+            'old_customer_amount' => $old_data[$employee_id]['total_amount'] ?? 0,
+            'assigned_customer_count' => $assigned_data[$employee_id]['customer_count'] ?? 0,
+            'assigned_customer_amount' => $assigned_data[$employee_id]['total_amount'] ?? 0
+        ];
+    }
+    
+    // 按总业绩降序排序
+    usort($combined_data, function($a, $b) {
+        return $b['total_amount'] - $a['total_amount'];
+    });
+    
+    return $combined_data;
+}
+
+/**
+ * 获取按月统计的客户构成业绩
+ */
+function getMonthlyCustomerComposition($conn, $start_date, $end_date, $employee_filter = null) {
+    // 查询每月新客户业绩(客户编码以0开头的)
+    $new_customer_sql = "SELECT 
+                DATE_FORMAT(o.order_date, '%Y-%m') AS month,
+                COUNT(DISTINCT c.id) AS customer_count,
+                SUM(o.total_amount) AS total_amount
+            FROM orders o
+            JOIN customer c ON o.customer_id = c.id
+            WHERE o.order_date BETWEEN '$start_date' AND '$end_date'
+            AND c.cs_deal = 3
+            AND c.cs_code LIKE '%.0%'";
+    
+    // 查询每月老客户业绩(客户编码以3开头且不包含斜杠的)
+    $old_customer_sql = "SELECT 
+                DATE_FORMAT(o.order_date, '%Y-%m') AS month,
+                COUNT(DISTINCT c.id) AS customer_count,
+                SUM(o.total_amount) AS total_amount
+            FROM orders o
+            JOIN customer c ON o.customer_id = c.id
+            WHERE o.order_date BETWEEN '$start_date' AND '$end_date'
+            AND c.cs_deal = 3
+            AND c.cs_code LIKE '%.3%'
+            AND c.cs_code NOT LIKE '%/%'";
+    
+    // 查询每月分配客户业绩(客户编码包含斜杠的)
+    $assigned_customer_sql = "SELECT 
+                DATE_FORMAT(o.order_date, '%Y-%m') AS month,
+                COUNT(DISTINCT c.id) AS customer_count,
+                SUM(o.total_amount) AS total_amount
+            FROM orders o
+            JOIN customer c ON o.customer_id = c.id
+            WHERE o.order_date BETWEEN '$start_date' AND '$end_date'
+            AND c.cs_deal = 3
+            AND c.cs_code LIKE '%/%'";
+    
+    // 查询每月总业绩
+    $total_sql = "SELECT 
+                DATE_FORMAT(o.order_date, '%Y-%m') AS month,
+                COUNT(DISTINCT c.id) AS customer_count,
+                SUM(o.total_amount) AS total_amount
+            FROM orders o
+            JOIN customer c ON o.customer_id = c.id
+            WHERE o.order_date BETWEEN '$start_date' AND '$end_date'
+            AND c.cs_deal = 3";
+    
+    // 根据员工过滤条件添加WHERE子句
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (!empty($employee_filter)) {
+                $employee_ids = implode(',', array_map('intval', $employee_filter));
+                $new_customer_sql .= " AND c.cs_belong IN ($employee_ids)";
+                $old_customer_sql .= " AND c.cs_belong IN ($employee_ids)";
+                $assigned_customer_sql .= " AND c.cs_belong IN ($employee_ids)";
+                $total_sql .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $employee_id = intval($employee_filter);
+            $new_customer_sql .= " AND c.cs_belong = $employee_id";
+            $old_customer_sql .= " AND c.cs_belong = $employee_id";
+            $assigned_customer_sql .= " AND c.cs_belong = $employee_id";
+            $total_sql .= " AND c.cs_belong = $employee_id";
+        }
+    }
+    
+    $new_customer_sql .= " GROUP BY DATE_FORMAT(o.order_date, '%Y-%m') ORDER BY month";
+    $old_customer_sql .= " GROUP BY DATE_FORMAT(o.order_date, '%Y-%m') ORDER BY month";
+    $assigned_customer_sql .= " GROUP BY DATE_FORMAT(o.order_date, '%Y-%m') ORDER BY month";
+    $total_sql .= " GROUP BY DATE_FORMAT(o.order_date, '%Y-%m') ORDER BY month";
+    
+    $new_result = $conn->query($new_customer_sql);
+    $old_result = $conn->query($old_customer_sql);
+    $assigned_result = $conn->query($assigned_customer_sql);
+    $total_result = $conn->query($total_sql);
+    
+    $new_data = [];
+    $old_data = [];
+    $assigned_data = [];
+    $total_data = [];
+    
+    if ($new_result) {
+        while ($row = $new_result->fetch_assoc()) {
+            $new_data[$row['month']] = $row;
+        }
+    }
+    
+    if ($old_result) {
+        while ($row = $old_result->fetch_assoc()) {
+            $old_data[$row['month']] = $row;
+        }
+    }
+    
+    if ($assigned_result) {
+        while ($row = $assigned_result->fetch_assoc()) {
+            $assigned_data[$row['month']] = $row;
+        }
+    }
+    
+    if ($total_result) {
+        while ($row = $total_result->fetch_assoc()) {
+            $total_data[$row['month']] = $row;
+        }
+    }
+    
+    // 合并数据
+    $combined_data = [];
+    
+    foreach ($total_data as $month => $total) {
+        $combined_data[$month] = [
+            'month' => $month,
+            'total_customer_count' => $total['customer_count'],
+            'total_amount' => $total['total_amount'],
+            'new_customer_count' => $new_data[$month]['customer_count'] ?? 0,
+            'new_customer_amount' => $new_data[$month]['total_amount'] ?? 0,
+            'old_customer_count' => $old_data[$month]['customer_count'] ?? 0,
+            'old_customer_amount' => $old_data[$month]['total_amount'] ?? 0,
+            'assigned_customer_count' => $assigned_data[$month]['customer_count'] ?? 0,
+            'assigned_customer_amount' => $assigned_data[$month]['total_amount'] ?? 0
+        ];
+    }
+    
+    // 按月份排序
+    ksort($combined_data);
+    
+    return array_values($combined_data);
+}
+
+/**
+ * 导出数据为CSV
+ */
+function exportToCSV($data, $columns, $filename) {
+    // 设置头信息
+    header('Content-Type: text/csv; charset=utf-8');
+    header('Content-Disposition: attachment;filename="' . $filename . '.csv"');
+    header('Cache-Control: max-age=0');
+    
+    // 创建输出流
+    $output = fopen('php://output', 'w');
+    
+    // 添加UTF-8 BOM以确保Excel正确显示中文
+    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
+    
+    // 输出列头
+    fputcsv($output, $columns);
+    
+    // 输出数据行
+    foreach ($data as $row) {
+        // 确保所有数据都是数组格式
+        $rowData = array_values($row);
+        fputcsv($output, $rowData);
+    }
+    
+    fclose($output);
+    exit;
+}
+
+/**
+ * 渲染业务员客户构成统计表格
+ */
+function renderCustomerCompositionTable($data, $is_export = false) {
+    if (empty($data)) {
+        if (!$is_export) {
+            echo '<div class="alert alert-info">当前选择范围内没有业绩数据</div>';
+        }
+        return;
+    }
+    
+    // 准备数据
+    $table_data = [];
+    
+    foreach ($data as $item) {
+        $table_data[] = [
+            '业务员' => $item['employee_name'],
+            '总业绩' => $is_export ? $item['total_amount'] : formatCurrency($item['total_amount']),
+            '新客户业绩' => $is_export ? $item['new_customer_amount'] : formatCurrency($item['new_customer_amount']),
+            '新客户占比' => $is_export ? ($item['total_amount'] > 0 ? ($item['new_customer_amount'] / $item['total_amount']) * 100 : 0) : formatPercentage($item['new_customer_amount'], $item['total_amount']),
+            '老客户业绩' => $is_export ? $item['old_customer_amount'] : formatCurrency($item['old_customer_amount']),
+            '老客户占比' => $is_export ? ($item['total_amount'] > 0 ? ($item['old_customer_amount'] / $item['total_amount']) * 100 : 0) : formatPercentage($item['old_customer_amount'], $item['total_amount']),
+            '分配客户业绩' => $is_export ? $item['assigned_customer_amount'] : formatCurrency($item['assigned_customer_amount']),
+            '分配客户占比' => $is_export ? ($item['total_amount'] > 0 ? ($item['assigned_customer_amount'] / $item['total_amount']) * 100 : 0) : formatPercentage($item['assigned_customer_amount'], $item['total_amount'])
+        ];
+    }
+    
+    // 如果是导出请求,则导出数据
+    if ($is_export) {
+        exportToCSV(
+            $table_data, 
+            ['业务员', '总业绩', '新客户业绩', '新客户占比(%)', '老客户业绩', '老客户占比(%)', '分配客户业绩', '分配客户占比(%)'],
+            '业务员客户构成统计_' . date('Ymd')
+        );
+        return;
+    }
+    
+    // 渲染表格
+    echo '<div class="row mt-5">';
+    echo '<div class="col-md-12">';
+    echo '<div class="card">';
+    echo '<div class="card-header d-flex justify-content-between align-items-center">';
+    echo '<span>业务员客户构成统计</span>';
+    echo '<a href="' . $_SERVER['REQUEST_URI'] . '&export=excel&type=employee" class="btn btn-sm btn-success ml-3">导出CSV</a>';
+    echo '</div>';
+    echo '<div class="card-body">';
+    echo '<div class="table-responsive">';
+    echo '<table class="table table-bordered table-striped">';
+    echo '<thead class="thead-light">';
+    echo '<tr>';
+    echo '<th style="width: 12%; text-align: left;">业务员</th>';
+    echo '<th style="width: 12%; text-align: left;">总业绩</th>';
+    echo '<th style="width: 12%; text-align: left;">新客户业绩</th>';
+    echo '<th style="width: 12%; text-align: left;">新客户占比</th>';
+    echo '<th style="width: 12%; text-align: left;">老客户业绩</th>';
+    echo '<th style="width: 12%; text-align: left;">老客户占比</th>';
+    echo '<th style="width: 12%; text-align: left;">分配客户业绩</th>';
+    echo '<th style="width: 12%; text-align: left;">分配客户占比</th>';
+    echo '</tr>';
+    echo '</thead>';
+    echo '<tbody>';
+    
+    foreach ($data as $item) {
+        echo '<tr>';
+        echo '<td>' . $item['employee_name'] . '</td>';
+        echo '<td>' . formatCurrency($item['total_amount']) . '</td>';
+        echo '<td>' . formatCurrency($item['new_customer_amount']) . '</td>';
+        echo '<td>' . formatPercentage($item['new_customer_amount'], $item['total_amount']) . '</td>';
+        echo '<td>' . formatCurrency($item['old_customer_amount']) . '</td>';
+        echo '<td>' . formatPercentage($item['old_customer_amount'], $item['total_amount']) . '</td>';
+        echo '<td>' . formatCurrency($item['assigned_customer_amount']) . '</td>';
+        echo '<td>' . formatPercentage($item['assigned_customer_amount'], $item['total_amount']) . '</td>';
+        echo '</tr>';
+    }
+    
+    echo '</tbody>';
+    echo '</table>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+}
+
+/**
+ * 渲染每月客户构成统计表格
+ */
+function renderMonthlyCustomerCompositionTable($data, $is_export = false) {
+    if (empty($data)) {
+        if (!$is_export) {
+            echo '<div class="alert alert-info">当前选择范围内没有月度业绩数据</div>';
+        }
+        return;
+    }
+    
+    // 准备数据
+    $table_data = [];
+    
+    foreach ($data as $item) {
+        $table_data[] = [
+            '月份' => $item['month'],
+            '总业绩' => $is_export ? $item['total_amount'] : formatCurrency($item['total_amount']),
+            '新客户业绩' => $is_export ? $item['new_customer_amount'] : formatCurrency($item['new_customer_amount']),
+            '新客户占比' => $is_export ? ($item['total_amount'] > 0 ? ($item['new_customer_amount'] / $item['total_amount']) * 100 : 0) : formatPercentage($item['new_customer_amount'], $item['total_amount']),
+            '老客户业绩' => $is_export ? $item['old_customer_amount'] : formatCurrency($item['old_customer_amount']),
+            '老客户占比' => $is_export ? ($item['total_amount'] > 0 ? ($item['old_customer_amount'] / $item['total_amount']) * 100 : 0) : formatPercentage($item['old_customer_amount'], $item['total_amount']),
+            '分配客户业绩' => $is_export ? $item['assigned_customer_amount'] : formatCurrency($item['assigned_customer_amount']),
+            '分配客户占比' => $is_export ? ($item['total_amount'] > 0 ? ($item['assigned_customer_amount'] / $item['total_amount']) * 100 : 0) : formatPercentage($item['assigned_customer_amount'], $item['total_amount'])
+        ];
+    }
+    
+    // 如果是导出请求,则导出数据
+    if ($is_export) {
+        exportToCSV(
+            $table_data, 
+            ['月份', '总业绩', '新客户业绩', '新客户占比(%)', '老客户业绩', '老客户占比(%)', '分配客户业绩', '分配客户占比(%)'],
+            '每月客户构成统计_' . date('Ymd')
+        );
+        return;
+    }
+    
+    // 渲染表格
+    echo '<div class="row mt-5 mb-5">';
+    echo '<div class="col-md-12">';
+    echo '<div class="card">';
+    echo '<div class="card-header d-flex justify-content-between align-items-center">';
+    echo '<span>每月客户构成统计</span>';
+    echo '<a href="' . $_SERVER['REQUEST_URI'] . '&export=excel&type=monthly" class="btn btn-sm btn-success ml-3">导出CSV</a>';
+    echo '</div>';
+    echo '<div class="card-body">';
+    echo '<div class="table-responsive">';
+    echo '<table class="table table-bordered table-striped">';
+    echo '<thead class="thead-light">';
+    echo '<tr>';
+    echo '<th style="width: 12%; text-align: left;">月份</th>';
+    echo '<th style="width: 12%; text-align: left;">总业绩</th>';
+    echo '<th style="width: 12%; text-align: left;">新客户业绩</th>';
+    echo '<th style="width: 12%; text-align: left;">新客户占比</th>';
+    echo '<th style="width: 12%; text-align: left;">老客户业绩</th>';
+    echo '<th style="width: 12%; text-align: left;">老客户占比</th>';
+    echo '<th style="width: 12%; text-align: left;">分配客户业绩</th>';
+    echo '<th style="width: 12%; text-align: left;">分配客户占比</th>';
+    echo '</tr>';
+    echo '</thead>';
+    echo '<tbody>';
+    
+    foreach ($data as $item) {
+        echo '<tr>';
+        echo '<td>' . $item['month'] . '</td>';
+        echo '<td>' . formatCurrency($item['total_amount']) . '</td>';
+        echo '<td>' . formatCurrency($item['new_customer_amount']) . '</td>';
+        echo '<td>' . formatPercentage($item['new_customer_amount'], $item['total_amount']) . '</td>';
+        echo '<td>' . formatCurrency($item['old_customer_amount']) . '</td>';
+        echo '<td>' . formatPercentage($item['old_customer_amount'], $item['total_amount']) . '</td>';
+        echo '<td>' . formatCurrency($item['assigned_customer_amount']) . '</td>';
+        echo '<td>' . formatPercentage($item['assigned_customer_amount'], $item['total_amount']) . '</td>';
+        echo '</tr>';
+    }
+    
+    echo '</tbody>';
+    echo '</table>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+}
+
+// 获取选择的业务员
+$selected_employee = isset($_GET['selected_employee']) ? $_GET['selected_employee'] : 'all';
+
+// 确定要显示哪些业务员的数据
+$employee_filter = null;
+
+if ($selected_employee != 'all') {
+    // 如果选择了特定业务员,则只显示该业务员的数据
+    $employee_filter = intval($selected_employee);
+} else {
+    // 否则按权限显示相应的业务员数据
+    if ($current_permission_role == 1) {
+        // 管理员可以看到所有业务员
+        $employee_filter = null;
+    } elseif ($current_permission_role == 2) {
+        // 组长可以看到自己和组员
+        $visible_employees = [];
+        $query = "SELECT id FROM employee WHERE id = " . intval($current_employee_id) . " OR em_role = " . intval($current_employee_id);
+        $result = $conn->query($query);
+        
+        if ($result) {
+            while ($row = $result->fetch_assoc()) {
+                $visible_employees[] = $row['id'];
+            }
+        }
+        
+        $employee_filter = $visible_employees;
+    } else {
+        // 组员只能看到自己
+        $employee_filter = intval($current_employee_id);
+    }
+}
+
+// 获取业务员客户构成统计数据
+$customer_composition_stats = getCustomerCompositionStats($conn, $start_date, $end_date, $employee_filter);
+
+// 获取每月客户构成统计数据
+$monthly_customer_composition = getMonthlyCustomerComposition($conn, $start_date, $end_date, $employee_filter);
+
+// 处理导出请求
+if ($is_export) {
+    $export_type = isset($_GET['type']) ? $_GET['type'] : '';
+    
+    switch ($export_type) {
+        case 'employee':
+            renderCustomerCompositionTable($customer_composition_stats, true);
+            break;
+        case 'monthly':
+            renderMonthlyCustomerCompositionTable($monthly_customer_composition, true);
+            break;
+    }
+    
+    exit; // 确保导出后停止执行
+}
+
+?>
+
+<div class="container">
+    <div class="page-header">
+        <h1 class="page-title">业绩客户构成统计</h1>
+    </div>
+    
+    <!-- 日期筛选 -->
+    <div class="filter-form mb-5">
+        <form method="get" class="filter-form-inline">
+            <div class="form-group mr-3">
+                <label for="date_range" class="mr-2">选择日期范围</label>
+                <select class="form-control" id="date_range" name="date_range" onchange="toggleCustomDates()">
+                    <option value="current_month" <?php echo $date_range == 'current_month' ? 'selected' : ''; ?>>本月</option>
+                    <option value="last_month" <?php echo $date_range == 'last_month' ? 'selected' : ''; ?>>上月</option>
+                    <option value="current_year" <?php echo $date_range == 'current_year' ? 'selected' : ''; ?>>今年</option>
+                    <option value="last_30_days" <?php echo $date_range == 'last_30_days' ? 'selected' : ''; ?>>最近30天</option>
+                    <option value="last_90_days" <?php echo $date_range == 'last_90_days' ? 'selected' : ''; ?>>最近90天</option>
+                    <option value="custom" <?php echo $date_range == 'custom' ? 'selected' : ''; ?>>自定义日期范围</option>
+                </select>
+            </div>
+            <div class="form-group custom-date-inputs mr-3" id="custom_start_date" style="display: <?php echo $date_range == 'custom' ? 'inline-block' : 'none'; ?>">
+                <label for="start_date" class="mr-2">开始日期</label>
+                <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo $date_params['custom_start']; ?>">
+            </div>
+            <div class="form-group custom-date-inputs mr-3" id="custom_end_date" style="display: <?php echo $date_range == 'custom' ? 'inline-block' : 'none'; ?>">
+                <label for="end_date" class="mr-2">结束日期</label>
+                <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo $date_params['custom_end']; ?>">
+            </div>
+            
+            <!-- 业务员选择 -->
+            <div class="form-group mr-3">
+                <label for="selected_employee" class="mr-2">选择业务员</label>
+                <select class="form-control" id="selected_employee" name="selected_employee">
+                    <option value="all">所有业务员</option>
+                    <?php
+                    // 获取当前用户可见的业务员列表
+                    $visible_employees_query = "";
+                    
+                    if ($current_permission_role == 1) {
+                        // 管理员可以看到所有业务员
+                        $visible_employees_query = "SELECT id, em_user FROM employee WHERE em_role IS NOT NULL ORDER BY em_user";
+                    } elseif ($current_permission_role == 2) {
+                        // 组长可以看到自己和组员
+                        $visible_employees_query = "SELECT id, em_user FROM employee WHERE id = $current_employee_id OR em_role = $current_employee_id ORDER BY em_user";
+                    } else {
+                        // 组员只能看到自己
+                        $visible_employees_query = "SELECT id, em_user FROM employee WHERE id = $current_employee_id";
+                    }
+                    
+                    $visible_employees_result = $conn->query($visible_employees_query);
+                    $selected_employee = isset($_GET['selected_employee']) ? $_GET['selected_employee'] : 'all';
+                    
+                    while ($emp = $visible_employees_result->fetch_assoc()) {
+                        $selected = ($selected_employee == $emp['id']) ? 'selected' : '';
+                        echo "<option value='".$emp['id']."' $selected>".$emp['em_user']."</option>";
+                    }
+                    ?>
+                </select>
+            </div>
+            
+            <div class="form-group">
+                <button type="submit" class="btn btn-primary">应用筛选</button>
+            </div>
+        </form>
+    </div>
+    
+    <!-- 统计内容区域 -->
+    <div class="stats-content">
+        <?php
+        // 渲染表格
+        renderCustomerCompositionTable($customer_composition_stats);
+        renderMonthlyCustomerCompositionTable($monthly_customer_composition);
+        ?>
+    </div>
+</div>
+
+<style>
+/* 添加一些额外的样式以改善表格显示 */
+.filter-form {
+    background-color: #f8f9fa;
+    padding: 20px;
+    border-radius: 5px;
+    margin-bottom: 30px;
+}
+
+.filter-form-inline {
+    display: flex;
+    flex-wrap: wrap;
+    align-items: flex-end;
+}
+
+.filter-form .form-group {
+    margin-bottom: 10px;
+    margin-right: 15px;
+}
+
+/* 表格样式 */
+.table {
+    width: 100%;
+    margin-bottom: 1rem;
+}
+
+.table th, .table td {
+    padding: 12px;
+    vertical-align: middle;
+}
+
+/* 确保表头也是左对齐 */
+.thead-light th {
+    background-color: #f8f9fa;
+    border-color: #dee2e6;
+    text-align: left;
+}
+
+.table-striped tbody tr:nth-of-type(odd) {
+    background-color: rgba(0, 0, 0, 0.03);
+}
+
+.card {
+    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
+}
+
+.card-header {
+    background-color: #f8f9fa;
+    padding: 15px;
+}
+
+.card-body {
+    padding: 1.5rem;
+}
+
+/* 添加按钮左边距 */
+.ml-3 {
+    margin-left: 15px !important;
+}
+
+/* 确保卡片头部布局正确 */
+.card-header.d-flex {
+    display: flex !important;
+    justify-content: space-between !important;
+    align-items: center !important;
+}
+</style>
+
+<script>
+function toggleCustomDates() {
+    const dateRange = document.getElementById('date_range').value;
+    const customDateInputs = document.querySelectorAll('.custom-date-inputs');
+    
+    if (dateRange === 'custom') {
+        customDateInputs.forEach(el => el.style.display = 'inline-block');
+    } else {
+        customDateInputs.forEach(el => el.style.display = 'none');
+    }
+}
+</script>
+
+<?php
+// 页面底部
+include('statistics_footer.php');
+?> 

+ 726 - 0
inquiry_conversion_stats.php

@@ -0,0 +1,726 @@
+<?php
+/**
+ * 询盘转化率统计分析
+ */
+require_once 'conn.php';
+require_once 'statistics_utils.php';
+require_once 'statistics_customers.php';
+require_once 'statistics_sales.php';
+// 检查登录状态
+if (!isset($_SESSION['employee_id'])) {
+    checkLogin();
+}
+
+function formatCurrency($value) {
+    return '¥' . number_format($value ?? 0, 2);
+}
+
+function formatPercentage($value) {
+    return number_format($value * 100, 2) . '%';
+}
+
+// 获取当前登录用户信息
+$current_employee_id = $_SESSION['employee_id'];
+$current_permission_role = 0;
+
+// 获取当前用户权限角色
+$current_employee_id = intval($current_employee_id); // 确保是整数
+$query = "SELECT em_permission_role_id FROM employee WHERE id = $current_employee_id";
+$result = $conn->query($query);
+if ($result && $row = $result->fetch_assoc()) {
+    $current_permission_role = $row['em_permission_role_id'];
+}
+
+// 检查是否为导出请求
+$is_export = isset($_GET['export']) && $_GET['export'] == 'excel';
+
+// 获取日期范围参数
+$date_params = getDateRangeParams();
+$start_date = $date_params['start_date_sql'];
+$end_date = $date_params['end_date_sql'];
+$date_range = $date_params['date_range'];
+$period = $date_params['period'];
+
+// 设置询盘回溯月份数
+$lookback_months = isset($_GET['lookback_months']) ? intval($_GET['lookback_months']) : 12;
+if ($lookback_months < 1) {
+    $lookback_months = 12; // 默认为12个月
+}
+
+// 如果不是导出操作,则包含页面头部
+if (!$is_export) {
+    include('statistics_header.php');
+}
+
+/**
+ * 获取按业务员统计的询盘转化率
+ */
+function getEmployeeInquiryConversionRate($conn, $start_date, $end_date, $lookback_months, $employee_filter = null, $channel_filter = null) {
+    // 计算回溯日期(X个月前)
+    $lookback_date = date('Y-m-d', strtotime($start_date . ' -' . $lookback_months . ' months'));
+    
+    $sql = "SELECT 
+                e.id AS employee_id,
+                e.em_user AS employee_name,
+                COUNT(DISTINCT CASE WHEN c.cs_deal = 3 AND c.cs_dealdate BETWEEN '$start_date' AND '$end_date' THEN c.id ELSE NULL END) AS deal_count,
+                COUNT(DISTINCT CASE WHEN c.cs_addtime BETWEEN '$lookback_date' AND '$end_date' THEN c.id ELSE NULL END) AS inquiry_count,
+                (SELECT ch_name FROM qudao WHERE id = c.cs_from) AS channel_name
+            FROM customer c
+            JOIN employee e ON c.cs_belong = e.id
+            WHERE c.cs_addtime BETWEEN '$lookback_date' AND '$end_date'";
+    
+    // 添加渠道筛选条件
+    if ($channel_filter !== null && $channel_filter != 'all') {
+        $sql .= " AND c.cs_from = " . intval($channel_filter);
+    }
+    
+    // 根据员工过滤条件添加WHERE子句
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (!empty($employee_filter)) {
+                $employee_ids = implode(',', array_map('intval', $employee_filter));
+                $sql .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql .= " AND c.cs_belong = " . intval($employee_filter);
+        }
+    }
+    
+    $sql .= " GROUP BY e.id, c.cs_from
+              ORDER BY e.em_user";
+    
+    $result = $conn->query($sql);
+    $data = [];
+    
+    if ($result) {
+        while ($row = $result->fetch_assoc()) {
+            // 计算转化率
+            $conversion_rate = $row['inquiry_count'] > 0 ? $row['deal_count'] / $row['inquiry_count'] : 0;
+            $row['conversion_rate'] = $conversion_rate;
+            $data[] = $row;
+        }
+    }
+    
+    return $data;
+}
+
+/**
+ * 获取按国家和渠道统计的询盘转化率
+ */
+function getCountryChannelConversionRate($conn, $start_date, $end_date, $lookback_months, $employee_filter = null, $channel_filter = null) {
+    // 计算回溯日期(X个月前)
+    $lookback_date = date('Y-m-d', strtotime($start_date . ' -' . $lookback_months . ' months'));
+    
+    $sql = "SELECT 
+                co.id AS country_id,
+                co.countryName AS country_name,
+                q.id AS channel_id,
+                q.ch_name AS channel_name,
+                COUNT(DISTINCT CASE WHEN c.cs_deal = 3 AND c.cs_dealdate BETWEEN '$start_date' AND '$end_date' THEN c.id ELSE NULL END) AS deal_count,
+                COUNT(DISTINCT CASE WHEN c.cs_addtime BETWEEN '$lookback_date' AND '$end_date' THEN c.id ELSE NULL END) AS inquiry_count,
+                DATE_FORMAT(c.cs_addtime, '%Y-%m') AS month
+            FROM customer c
+            JOIN country co ON c.cs_country = co.id
+            JOIN qudao q ON c.cs_from = q.id
+            WHERE c.cs_addtime BETWEEN '$lookback_date' AND '$end_date'";
+    
+    // 添加渠道筛选条件
+    if ($channel_filter !== null && $channel_filter != 'all') {
+        $sql .= " AND c.cs_from = " . intval($channel_filter);
+    }
+    
+    // 根据员工过滤条件添加WHERE子句
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (!empty($employee_filter)) {
+                $employee_ids = implode(',', array_map('intval', $employee_filter));
+                $sql .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql .= " AND c.cs_belong = " . intval($employee_filter);
+        }
+    }
+    
+    $sql .= " GROUP BY co.id, q.id, DATE_FORMAT(c.cs_addtime, '%Y-%m')
+              ORDER BY co.countryName, q.ch_name, month";
+    
+    $result = $conn->query($sql);
+    $data = [];
+    
+    if ($result) {
+        while ($row = $result->fetch_assoc()) {
+            // 计算转化率
+            $conversion_rate = $row['inquiry_count'] > 0 ? $row['deal_count'] / $row['inquiry_count'] : 0;
+            $row['conversion_rate'] = $conversion_rate;
+            $data[] = $row;
+        }
+    }
+    
+    return $data;
+}
+
+/**
+ * 获取按渠道统计的累计询盘转化率
+ */
+function getChannelTotalConversionRate($conn, $start_date, $end_date, $lookback_months, $employee_filter = null, $channel_filter = null) {
+    // 计算回溯日期(X个月前)
+    $lookback_date = date('Y-m-d', strtotime($start_date . ' -' . $lookback_months . ' months'));
+    
+    $sql = "SELECT 
+                q.id AS channel_id,
+                q.ch_name AS channel_name,
+                COUNT(DISTINCT CASE WHEN c.cs_deal = 3 AND c.cs_dealdate BETWEEN '$start_date' AND '$end_date' THEN c.id ELSE NULL END) AS deal_count,
+                COUNT(DISTINCT CASE WHEN c.cs_addtime BETWEEN '$lookback_date' AND '$end_date' THEN c.id ELSE NULL END) AS inquiry_count
+            FROM customer c
+            JOIN qudao q ON c.cs_from = q.id
+            WHERE c.cs_addtime BETWEEN '$lookback_date' AND '$end_date'";
+    
+    // 添加渠道筛选条件
+    if ($channel_filter !== null && $channel_filter != 'all') {
+        $sql .= " AND c.cs_from = " . intval($channel_filter);
+    }
+    
+    // 根据员工过滤条件添加WHERE子句
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (!empty($employee_filter)) {
+                $employee_ids = implode(',', array_map('intval', $employee_filter));
+                $sql .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql .= " AND c.cs_belong = " . intval($employee_filter);
+        }
+    }
+    
+    $sql .= " GROUP BY q.id
+              ORDER BY q.ch_name";
+    
+    $result = $conn->query($sql);
+    $data = [];
+    
+    if ($result) {
+        while ($row = $result->fetch_assoc()) {
+            // 计算转化率
+            $conversion_rate = $row['inquiry_count'] > 0 ? $row['deal_count'] / $row['inquiry_count'] : 0;
+            $row['conversion_rate'] = $conversion_rate;
+            $data[] = $row;
+        }
+    }
+    
+    return $data;
+}
+
+/**
+ * 导出数据为CSV
+ */
+function exportToCSV($data, $columns, $filename) {
+    // 设置头信息
+    header('Content-Type: text/csv; charset=utf-8');
+    header('Content-Disposition: attachment;filename="' . $filename . '.csv"');
+    header('Cache-Control: max-age=0');
+    
+    // 创建输出流
+    $output = fopen('php://output', 'w');
+    
+    // 添加UTF-8 BOM以确保Excel正确显示中文
+    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
+    
+    // 输出列头
+    fputcsv($output, $columns);
+    
+    // 输出数据行
+    foreach ($data as $row) {
+        // 确保所有数据都是数组格式
+        $rowData = array_values($row);
+        fputcsv($output, $rowData);
+    }
+    
+    fclose($output);
+    exit;
+}
+
+/**
+ * 渲染业务员询盘转化率表格
+ */
+function renderEmployeeConversionRateTable($data, $is_export = false) {
+    if (empty($data)) {
+        if (!$is_export) {
+            echo '<div class="alert alert-info">当前选择范围内没有业务员询盘转化率数据</div>';
+        }
+        return;
+    }
+    
+    // 准备数据
+    $table_data = [];
+    
+    foreach ($data as $item) {
+        $table_data[] = [
+            '业务员' => $item['employee_name'],
+            '渠道' => $item['channel_name'] ?? '未知',
+            '询盘数量' => $item['inquiry_count'],
+            '成交数量' => $item['deal_count'],
+            '转化率' => $is_export ? $item['conversion_rate'] : formatPercentage($item['conversion_rate'])
+        ];
+    }
+    
+    // 如果是导出请求,则导出数据
+    if ($is_export) {
+        exportToCSV(
+            $table_data, 
+            ['业务员', '渠道', '询盘数量', '成交数量', '转化率'],
+            '业务员询盘转化率_' . date('Ymd')
+        );
+        return;
+    }
+    
+    // 渲染表格
+    echo '<div class="row mt-5 mb-5">';
+    echo '<div class="col-md-12">';
+    echo '<div class="card">';
+    echo '<div class="card-header d-flex justify-content-between align-items-center">';
+    echo '<span>业务员询盘转化率统计</span>';
+    echo '<a href="' . $_SERVER['REQUEST_URI'] . '&export=excel&type=employee" class="btn btn-sm btn-success ml-3">导出CSV</a>';
+    echo '</div>';
+    echo '<div class="card-body">';
+    echo '<div class="table-responsive">';
+    echo '<table class="table table-bordered table-striped">';
+    echo '<thead class="thead-light">';
+    echo '<tr>';
+    echo '<th style="width: 20%; text-align: left;">业务员</th>';
+    echo '<th style="width: 20%; text-align: left;">渠道</th>';
+    echo '<th style="width: 20%; text-align: left;">询盘数量</th>';
+    echo '<th style="width: 20%; text-align: left;">成交数量</th>';
+    echo '<th style="width: 20%; text-align: left;">转化率</th>';
+    echo '</tr>';
+    echo '</thead>';
+    echo '<tbody>';
+    
+    foreach ($data as $item) {
+        echo '<tr>';
+        echo '<td>'.$item['employee_name'].'</td>';
+        echo '<td>'.($item['channel_name'] ?? '未知').'</td>';
+        echo '<td>'.$item['inquiry_count'].'</td>';
+        echo '<td>'.$item['deal_count'].'</td>';
+        echo '<td>'.formatPercentage($item['conversion_rate']).'</td>';
+        echo '</tr>';
+    }
+    
+    echo '</tbody>';
+    echo '</table>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+}
+
+/**
+ * 渲染渠道累计转化率表格
+ */
+function renderChannelTotalConversionRateTable($data, $is_export = false) {
+    if (empty($data)) {
+        if (!$is_export) {
+            echo '<div class="alert alert-info">当前选择范围内没有渠道转化率数据</div>';
+        }
+        return;
+    }
+    
+    // 准备数据
+    $table_data = [];
+    
+    foreach ($data as $item) {
+        $table_data[] = [
+            '渠道' => $item['channel_name'],
+            '询盘数量' => $item['inquiry_count'],
+            '成交数量' => $item['deal_count'],
+            '转化率' => $is_export ? $item['conversion_rate'] : formatPercentage($item['conversion_rate'])
+        ];
+    }
+    
+    // 如果是导出请求,则导出数据
+    if ($is_export) {
+        exportToCSV(
+            $table_data, 
+            ['渠道', '询盘数量', '成交数量', '转化率'],
+            '渠道询盘转化率_' . date('Ymd')
+        );
+        return;
+    }
+    
+    // 渲染表格
+    echo '<div class="row mt-5">';
+    echo '<div class="col-md-12">';
+    echo '<div class="card">';
+    echo '<div class="card-header d-flex justify-content-between align-items-center">';
+    echo '<span>渠道询盘转化率汇总</span>';
+    echo '<a href="' . $_SERVER['REQUEST_URI'] . '&export=excel&type=channel" class="btn btn-sm btn-success ml-3">导出CSV</a>';
+    echo '</div>';
+    echo '<div class="card-body">';
+    echo '<div class="table-responsive">';
+    echo '<table class="table table-bordered table-striped">';
+    echo '<thead class="thead-light">';
+    echo '<tr>';
+    echo '<th style="width: 25%; text-align: left;">渠道</th>';
+    echo '<th style="width: 25%; text-align: left;">询盘数量</th>';
+    echo '<th style="width: 25%; text-align: left;">成交数量</th>';
+    echo '<th style="width: 25%; text-align: left;">转化率</th>';
+    echo '</tr>';
+    echo '</thead>';
+    echo '<tbody>';
+    
+    foreach ($data as $item) {
+        echo '<tr>';
+        echo '<td>'.$item['channel_name'].'</td>';
+        echo '<td>'.$item['inquiry_count'].'</td>';
+        echo '<td>'.$item['deal_count'].'</td>';
+        echo '<td>'.formatPercentage($item['conversion_rate']).'</td>';
+        echo '</tr>';
+    }
+    
+    echo '</tbody>';
+    echo '</table>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+}
+
+/**
+ * 渲染国家/渠道月度转化率表格
+ */
+function renderCountryChannelConversionRateTable($data, $is_export = false) {
+    if (empty($data)) {
+        if (!$is_export) {
+            echo '<div class="alert alert-info">当前选择范围内没有国家/渠道月度转化率数据</div>';
+        }
+        return;
+    }
+    
+    // 准备数据
+    $table_data = [];
+    
+    foreach ($data as $item) {
+        $table_data[] = [
+            '国家' => $item['country_name'],
+            '渠道' => $item['channel_name'],
+            '月份' => $item['month'],
+            '询盘数量' => $item['inquiry_count'],
+            '成交数量' => $item['deal_count'],
+            '转化率' => $is_export ? $item['conversion_rate'] : formatPercentage($item['conversion_rate'])
+        ];
+    }
+    
+    // 如果是导出请求,则导出数据
+    if ($is_export) {
+        exportToCSV(
+            $table_data,
+            ['国家', '渠道', '月份', '询盘数量', '成交数量', '转化率'],
+            '国家渠道月度转化率_' . date('Ymd')
+        );
+        return;
+    }
+    
+    // 渲染表格
+    echo '<div class="row mt-5">';
+    echo '<div class="col-md-12">';
+    echo '<div class="card">';
+    echo '<div class="card-header d-flex justify-content-between align-items-center">';
+    echo '<span>国家/渠道月度转化率明细</span>';
+    echo '<a href="' . $_SERVER['REQUEST_URI'] . '&export=excel&type=country_channel" class="btn btn-sm btn-success ml-3">导出CSV</a>';
+    echo '</div>';
+    echo '<div class="card-body">';
+    echo '<div class="table-responsive">';
+    echo '<table class="table table-bordered table-striped">';
+    echo '<thead class="thead-light">';
+    echo '<tr>';
+    echo '<th style="width: 15%; text-align: left;">国家</th>';
+    echo '<th style="width: 15%; text-align: left;">渠道</th>';
+    echo '<th style="width: 15%; text-align: left;">月份</th>';
+    echo '<th style="width: 15%; text-align: left;">询盘数量</th>';
+    echo '<th style="width: 15%; text-align: left;">成交数量</th>';
+    echo '<th style="width: 15%; text-align: left;">转化率</th>';
+    echo '</tr>';
+    echo '</thead>';
+    echo '<tbody>';
+    
+    foreach ($data as $item) {
+        echo '<tr>';
+        echo '<td>' . $item['country_name'] . '</td>';
+        echo '<td>' . $item['channel_name'] . '</td>';
+        echo '<td>' . $item['month'] . '</td>';
+        echo '<td>' . $item['inquiry_count'] . '</td>';
+        echo '<td>' . $item['deal_count'] . '</td>';
+        echo '<td>' . formatPercentage($item['conversion_rate']) . '</td>';
+        echo '</tr>';
+    }
+    
+    echo '</tbody>';
+    echo '</table>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+}
+
+// 获取选择的业务员
+$selected_employee = isset($_GET['selected_employee']) ? $_GET['selected_employee'] : 'all';
+
+// 获取选择的渠道
+$selected_channel = isset($_GET['selected_channel']) ? $_GET['selected_channel'] : 'all';
+
+// 确定要显示哪些业务员的数据
+$employee_filter = null;
+
+if ($selected_employee != 'all') {
+    // 如果选择了特定业务员,则只显示该业务员的数据
+    $employee_filter = intval($selected_employee);
+} else {
+    // 否则按权限显示相应的业务员数据
+    if ($current_permission_role == 1) {
+        // 管理员可以看到所有业务员
+        $employee_filter = null;
+    } elseif ($current_permission_role == 2) {
+        // 组长可以看到自己和组员
+        $visible_employees = [];
+        $query = "SELECT id FROM employee WHERE id = " . intval($current_employee_id) . " OR em_role = " . intval($current_employee_id);
+        $result = $conn->query($query);
+        
+        if ($result) {
+            while ($row = $result->fetch_assoc()) {
+                $visible_employees[] = $row['id'];
+            }
+        }
+        
+        $employee_filter = $visible_employees;
+    } else {
+        // 组员只能看到自己
+        $employee_filter = intval($current_employee_id);
+    }
+}
+
+// 获取业务员询盘转化率数据
+$employee_conversion_rate = getEmployeeInquiryConversionRate($conn, $start_date, $end_date, $lookback_months, $employee_filter, $selected_channel);
+
+// 获取渠道累计转化率数据
+$channel_total_conversion_rate = getChannelTotalConversionRate($conn, $start_date, $end_date, $lookback_months, $employee_filter, $selected_channel);
+
+// 获取国家/渠道月度转化率数据
+$country_channel_conversion_rate = getCountryChannelConversionRate($conn, $start_date, $end_date, $lookback_months, $employee_filter, $selected_channel);
+
+// 处理导出请求
+if ($is_export) {
+    $export_type = isset($_GET['type']) ? $_GET['type'] : '';
+    
+    switch ($export_type) {
+        case 'employee':
+            renderEmployeeConversionRateTable($employee_conversion_rate, true);
+            break;
+        case 'channel':
+            renderChannelTotalConversionRateTable($channel_total_conversion_rate, true);
+            break;
+        case 'country_channel':
+            renderCountryChannelConversionRateTable($country_channel_conversion_rate, true);
+            break;
+    }
+    
+    exit; // 确保导出后停止执行
+}
+
+?>
+
+<div class="container">
+    <div class="page-header">
+        <h1 class="page-title">询盘转化率统计</h1>
+    </div>
+    
+    <!-- 日期筛选 -->
+    <div class="filter-form mb-5">
+        <form method="get" class="filter-form-inline">
+            <div class="form-group mr-3">
+                <label for="date_range" class="mr-2">选择日期范围</label>
+                <select class="form-control" id="date_range" name="date_range" onchange="toggleCustomDates()">
+                    <option value="current_month" <?php echo $date_range == 'current_month' ? 'selected' : ''; ?>>本月</option>
+                    <option value="last_month" <?php echo $date_range == 'last_month' ? 'selected' : ''; ?>>上月</option>
+                    <option value="current_year" <?php echo $date_range == 'current_year' ? 'selected' : ''; ?>>今年</option>
+                    <option value="last_30_days" <?php echo $date_range == 'last_30_days' ? 'selected' : ''; ?>>最近30天</option>
+                    <option value="last_90_days" <?php echo $date_range == 'last_90_days' ? 'selected' : ''; ?>>最近90天</option>
+                    <option value="custom" <?php echo $date_range == 'custom' ? 'selected' : ''; ?>>自定义日期范围</option>
+                </select>
+            </div>
+            <div class="form-group custom-date-inputs mr-3" id="custom_start_date" style="display: <?php echo $date_range == 'custom' ? 'inline-block' : 'none'; ?>">
+                <label for="start_date" class="mr-2">开始日期</label>
+                <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo $date_params['custom_start']; ?>">
+            </div>
+            <div class="form-group custom-date-inputs mr-3" id="custom_end_date" style="display: <?php echo $date_range == 'custom' ? 'inline-block' : 'none'; ?>">
+                <label for="end_date" class="mr-2">结束日期</label>
+                <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo $date_params['custom_end']; ?>">
+            </div>
+            
+            <!-- 回溯月份数选择 -->
+            <div class="form-group mr-3">
+                <label for="lookback_months" class="mr-2">回溯月数</label>
+                <select class="form-control" id="lookback_months" name="lookback_months">
+                    <option value="3" <?php echo $lookback_months == 3 ? 'selected' : ''; ?>>3个月</option>
+                    <option value="6" <?php echo $lookback_months == 6 ? 'selected' : ''; ?>>6个月</option>
+                    <option value="12" <?php echo $lookback_months == 12 ? 'selected' : ''; ?>>12个月</option>
+                    <option value="24" <?php echo $lookback_months == 24 ? 'selected' : ''; ?>>24个月</option>
+                </select>
+            </div>
+            
+            <!-- 业务员选择 -->
+            <div class="form-group mr-3">
+                <label for="selected_employee" class="mr-2">选择业务员</label>
+                <select class="form-control" id="selected_employee" name="selected_employee">
+                    <option value="all">所有业务员</option>
+                    <?php
+                    // 获取当前用户可见的业务员列表
+                    $visible_employees_query = "";
+                    
+                    if ($current_permission_role == 1) {
+                        // 管理员可以看到所有业务员
+                        $visible_employees_query = "SELECT id, em_user FROM employee WHERE em_role IS NOT NULL ORDER BY em_user";
+                    } elseif ($current_permission_role == 2) {
+                        // 组长可以看到自己和组员
+                        $visible_employees_query = "SELECT id, em_user FROM employee WHERE id = $current_employee_id OR em_role = $current_employee_id ORDER BY em_user";
+                    } else {
+                        // 组员只能看到自己
+                        $visible_employees_query = "SELECT id, em_user FROM employee WHERE id = $current_employee_id";
+                    }
+                    
+                    $visible_employees_result = $conn->query($visible_employees_query);
+                    $selected_employee = isset($_GET['selected_employee']) ? $_GET['selected_employee'] : 'all';
+                    
+                    while ($emp = $visible_employees_result->fetch_assoc()) {
+                        $selected = ($selected_employee == $emp['id']) ? 'selected' : '';
+                        echo "<option value='".$emp['id']."' $selected>".$emp['em_user']."</option>";
+                    }
+                    ?>
+                </select>
+            </div>
+            
+            <!-- 渠道选择 -->
+            <div class="form-group mr-3">
+                <label for="selected_channel" class="mr-2">选择渠道</label>
+                <select class="form-control" id="selected_channel" name="selected_channel">
+                    <option value="all">所有渠道</option>
+                    <?php
+                    // 获取渠道列表
+                    $channels_query = "SELECT id, ch_name FROM qudao ORDER BY ch_name";
+                    $channels_result = $conn->query($channels_query);
+                    
+                    while ($channel = $channels_result->fetch_assoc()) {
+                        $selected = ($selected_channel == $channel['id']) ? 'selected' : '';
+                        echo "<option value='".$channel['id']."' $selected>".$channel['ch_name']."</option>";
+                    }
+                    ?>
+                </select>
+            </div>
+            
+            <div class="form-group">
+                <button type="submit" class="btn btn-primary">应用筛选</button>
+            </div>
+        </form>
+    </div>
+    
+    <!-- 统计内容区域 -->
+    <div class="stats-content">
+        <?php
+        // 渲染渠道累计转化率表格
+        renderChannelTotalConversionRateTable($channel_total_conversion_rate);
+        
+        // 渲染业务员询盘转化率表格
+        renderEmployeeConversionRateTable($employee_conversion_rate);
+        
+        // 渲染国家/渠道月度转化率表格
+        renderCountryChannelConversionRateTable($country_channel_conversion_rate);
+        ?>
+    </div>
+</div>
+
+<style>
+/* 添加一些额外的样式以改善表格显示 */
+.filter-form {
+    background-color: #f8f9fa;
+    padding: 20px;
+    border-radius: 5px;
+    margin-bottom: 30px;
+}
+
+.filter-form-inline {
+    display: flex;
+    flex-wrap: wrap;
+    align-items: flex-end;
+}
+
+.filter-form .form-group {
+    margin-bottom: 10px;
+    margin-right: 15px;
+}
+
+/* 表格样式 */
+.table {
+    width: 100%;
+    margin-bottom: 1rem;
+}
+
+.table th, .table td {
+    padding: 12px;
+    vertical-align: middle;
+}
+
+/* 确保表头也是左对齐 */
+.thead-light th {
+    background-color: #f8f9fa;
+    border-color: #dee2e6;
+    text-align: left;
+}
+
+.table-striped tbody tr:nth-of-type(odd) {
+    background-color: rgba(0, 0, 0, 0.03);
+}
+
+.card {
+    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
+}
+
+.card-header {
+    background-color: #f8f9fa;
+    padding: 15px;
+}
+
+.card-body {
+    padding: 1.5rem;
+}
+
+/* 添加按钮左边距 */
+.ml-3 {
+    margin-left: 15px !important;
+}
+
+/* 确保卡片头部布局正确 */
+.card-header.d-flex {
+    display: flex !important;
+    justify-content: space-between !important;
+    align-items: center !important;
+}
+</style>
+
+<script>
+function toggleCustomDates() {
+    const dateRange = document.getElementById('date_range').value;
+    const customDateInputs = document.querySelectorAll('.custom-date-inputs');
+    
+    if (dateRange === 'custom') {
+        customDateInputs.forEach(el => el.style.display = 'inline-block');
+    } else {
+        customDateInputs.forEach(el => el.style.display = 'none');
+    }
+}
+</script>
+
+<?php
+// 页面底部
+include('statistics_footer.php');
+?> 

+ 513 - 0
monthly_deal_stats.php

@@ -0,0 +1,513 @@
+<?php
+/**
+ * 每月新增成交客户统计分析
+ */
+require_once 'conn.php';
+require_once 'statistics_utils.php';
+require_once 'statistics_customers.php';
+require_once 'statistics_sales.php';
+// 检查登录状态
+if (!isset($_SESSION['employee_id'])) {
+    checkLogin();
+}
+
+function formatCurrency($value) {
+    return '¥' . number_format($value ?? 0, 2);
+}
+
+// 获取当前登录用户信息
+$current_employee_id = $_SESSION['employee_id'];
+$current_permission_role = 0;
+
+// 获取当前用户权限角色
+$current_employee_id = intval($current_employee_id); // 确保是整数
+$query = "SELECT em_permission_role_id FROM employee WHERE id = $current_employee_id";
+$result = $conn->query($query);
+if ($result && $row = $result->fetch_assoc()) {
+    $current_permission_role = $row['em_permission_role_id'];
+}
+
+// 检查是否为导出请求
+$is_export = isset($_GET['export']) && $_GET['export'] == 'excel';
+
+// 获取日期范围参数
+$date_params = getDateRangeParams();
+$start_date = $date_params['start_date_sql'];
+$end_date = $date_params['end_date_sql'];
+$date_range = $date_params['date_range'];
+$period = $date_params['period'];
+
+// 如果不是导出操作,则包含页面头部
+if (!$is_export) {
+    include('statistics_header.php');
+}
+
+/**
+ * 获取每月新增成交客户数量
+ */
+function getMonthlyDealCustomers($conn, $start_date, $end_date, $employee_filter = null) {
+    $sql = "SELECT 
+                DATE_FORMAT(cs_dealdate, '%Y-%m') AS month,
+                COUNT(*) AS customer_count
+            FROM customer
+            WHERE cs_dealdate BETWEEN '$start_date' AND '$end_date'
+            AND cs_deal = 3";
+    
+    // 根据员工过滤条件添加WHERE子句
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (!empty($employee_filter)) {
+                $employee_ids = implode(',', array_map('intval', $employee_filter));
+                $sql .= " AND cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql .= " AND cs_belong = " . intval($employee_filter);
+        }
+    }
+    
+    $sql .= " GROUP BY DATE_FORMAT(cs_dealdate, '%Y-%m')
+              ORDER BY month";
+
+    $result = $conn->query($sql);
+    $data = [];
+    
+    if ($result) {
+        while ($row = $result->fetch_assoc()) {
+            $data[] = $row;
+        }
+    }
+    
+    return $data;
+}
+
+/**
+ * 获取按业务员统计的成交客户数量和金额
+ */
+function getDealStatsByEmployee($conn, $start_date, $end_date, $employee_filter = null) {
+    $sql = "SELECT 
+                e.id AS employee_id,
+                e.em_user AS employee_name,
+                COUNT(DISTINCT c.id) AS customer_count,
+                SUM(o.total_amount) AS total_amount
+            FROM orders o
+            JOIN customer c ON o.customer_id = c.id
+            JOIN employee e ON c.cs_belong = e.id
+            WHERE o.order_date BETWEEN '$start_date' AND '$end_date'
+            AND c.cs_deal = 3
+            AND c.cs_dealdate BETWEEN '$start_date' AND '$end_date'";
+    
+    // 根据员工过滤条件添加WHERE子句
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (!empty($employee_filter)) {
+                $employee_ids = implode(',', array_map('intval', $employee_filter));
+                $sql .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql .= " AND c.cs_belong = " . intval($employee_filter);
+        }
+    }
+    
+    $sql .= " GROUP BY e.id
+              ORDER BY total_amount DESC";
+    
+    $result = $conn->query($sql);
+    $data = [];
+    
+    if ($result) {
+        while ($row = $result->fetch_assoc()) {
+            $data[] = $row;
+        }
+    }
+    
+    return $data;
+}
+
+/**
+ * 导出数据为CSV
+ */
+function exportToCSV($data, $columns, $filename) {
+    // 设置头信息
+    header('Content-Type: text/csv; charset=utf-8');
+    header('Content-Disposition: attachment;filename="' . $filename . '.csv"');
+    header('Cache-Control: max-age=0');
+    
+    // 创建输出流
+    $output = fopen('php://output', 'w');
+    
+    // 添加UTF-8 BOM以确保Excel正确显示中文
+    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
+    
+    // 输出列头
+    fputcsv($output, $columns);
+    
+    // 输出数据行
+    foreach ($data as $row) {
+        // 确保所有数据都是数组格式
+        $rowData = array_values($row);
+        fputcsv($output, $rowData);
+    }
+    
+    fclose($output);
+    exit;
+}
+
+/**
+ * 渲染每月成交客户数量表格
+ */
+function renderMonthlyDealCustomersTable($data, $is_export = false) {
+    if (empty($data)) {
+        if (!$is_export) {
+            echo '<div class="alert alert-info">当前选择范围内没有成交客户数据</div>';
+        }
+        return;
+    }
+    
+    // 准备数据
+    $table_data = [];
+    $total_customers = 0;
+    
+    foreach ($data as $item) {
+        $table_data[] = [
+            '月份' => $item['month'],
+            '新增成交客户数量' => $item['customer_count']
+        ];
+        $total_customers += intval($item['customer_count']);
+    }
+    
+    // 如果是导出请求,则导出数据
+    if ($is_export) {
+        exportToCSV(
+            $table_data, 
+            ['月份', '新增成交客户数量'], 
+            '每月新增成交客户数量_' . date('Ymd')
+        );
+        return;
+    }
+    
+    // 渲染表格
+    echo '<div class="row mt-5 mb-5">';
+    echo '<div class="col-md-12">';
+    echo '<div class="card">';
+    echo '<div class="card-header d-flex justify-content-between align-items-center">';
+    echo '<span>每月新增成交客户数量明细 (总计: '.$total_customers.' 客户)</span>';
+    echo '<a href="' . $_SERVER['REQUEST_URI'] . '&export=excel&type=customers" class="btn btn-sm btn-success ml-3">导出CSV</a>';
+    echo '</div>';
+    echo '<div class="card-body">';
+    echo '<div class="table-responsive">';
+    echo '<table class="table table-bordered table-striped">';
+    echo '<thead class="thead-light">';
+    echo '<tr>';
+    echo '<th style="width: 50%; text-align: left;">月份</th>';
+    echo '<th style="width: 50%; text-align: left;">新增成交客户数量</th>';
+    echo '</tr>';
+    echo '</thead>';
+    echo '<tbody>';
+    
+    foreach ($data as $item) {
+        echo '<tr>';
+        echo '<td>'.$item['month'].'</td>';
+        echo '<td>'.$item['customer_count'].'</td>';
+        echo '</tr>';
+    }
+    
+    echo '</tbody>';
+    echo '</table>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+}
+
+/**
+ * 渲染业务员成交统计表格
+ */
+function renderDealStatsByEmployeeTable($data, $is_export = false) {
+    if (empty($data)) {
+        if (!$is_export) {
+            echo '<div class="alert alert-info">当前选择范围内没有业务员成交数据</div>';
+        }
+        return;
+    }
+    
+    // 准备数据
+    $table_data = [];
+    
+    foreach ($data as $item) {
+        $avg_customer_value = $item['customer_count'] > 0 ? $item['total_amount'] / $item['customer_count'] : 0;
+        $table_data[] = [
+            '业务员' => $item['employee_name'],
+            '成交客户数' => $item['customer_count'],
+            '成交金额' => $is_export ? $item['total_amount'] : formatCurrency($item['total_amount']),
+            '客单价' => $is_export ? $avg_customer_value : formatCurrency($avg_customer_value)
+        ];
+    }
+    
+    // 如果是导出请求,则导出数据
+    if ($is_export) {
+        exportToCSV(
+            $table_data, 
+            ['业务员', '成交客户数', '成交金额', '客单价'],
+            '业务员成交统计_' . date('Ymd')
+        );
+        return;
+    }
+    
+    // 渲染表格
+    echo '<div class="row mt-5">';
+    echo '<div class="col-md-12">';
+    echo '<div class="card">';
+    echo '<div class="card-header d-flex justify-content-between align-items-center">';
+    echo '<span>业务员成交统计明细</span>';
+    echo '<a href="' . $_SERVER['REQUEST_URI'] . '&export=excel&type=employee" class="btn btn-sm btn-success ml-3">导出CSV</a>';
+    echo '</div>';
+    echo '<div class="card-body">';
+    echo '<div class="table-responsive">';
+    echo '<table class="table table-bordered table-striped">';
+    echo '<thead class="thead-light">';
+    echo '<tr>';
+    echo '<th style="width: 25%; text-align: left;">业务员</th>';
+    echo '<th style="width: 25%; text-align: left;">成交客户数</th>';
+    echo '<th style="width: 25%; text-align: left;">成交金额</th>';
+    echo '<th style="width: 25%; text-align: left;">客单价</th>';
+    echo '</tr>';
+    echo '</thead>';
+    echo '<tbody>';
+    
+    foreach ($data as $item) {
+        $avg_customer_value = $item['customer_count'] > 0 ? $item['total_amount'] / $item['customer_count'] : 0;
+        echo '<tr>';
+        echo '<td>'.$item['employee_name'].'</td>';
+        echo '<td>'.$item['customer_count'].'</td>';
+        echo '<td>'.formatCurrency($item['total_amount']).'</td>';
+        echo '<td>'.formatCurrency($avg_customer_value).'</td>';
+        echo '</tr>';
+    }
+    
+    echo '</tbody>';
+    echo '</table>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+}
+
+// 获取选择的业务员
+$selected_employee = isset($_GET['selected_employee']) ? $_GET['selected_employee'] : 'all';
+
+// 确定要显示哪些业务员的数据
+$employee_filter = null;
+
+if ($selected_employee != 'all') {
+    // 如果选择了特定业务员,则只显示该业务员的数据
+    $employee_filter = intval($selected_employee);
+} else {
+    // 否则按权限显示相应的业务员数据
+    if ($current_permission_role == 1) {
+        // 管理员可以看到所有业务员
+        $employee_filter = null;
+    } elseif ($current_permission_role == 2) {
+        // 组长可以看到自己和组员
+        $visible_employees = [];
+        $query = "SELECT id FROM employee WHERE id = " . intval($current_employee_id) . " OR em_role = " . intval($current_employee_id);
+        $result = $conn->query($query);
+        
+        if ($result) {
+            while ($row = $result->fetch_assoc()) {
+                $visible_employees[] = $row['id'];
+            }
+        }
+        
+        $employee_filter = $visible_employees;
+    } else {
+        // 组员只能看到自己
+        $employee_filter = intval($current_employee_id);
+    }
+}
+
+// 获取每月新增成交客户数量数据
+$monthly_deal_customers = getMonthlyDealCustomers($conn, $start_date, $end_date, $employee_filter);
+
+// 获取业务员成交统计数据
+$deal_stats_by_employee = getDealStatsByEmployee($conn, $start_date, $end_date, $employee_filter);
+
+// 处理导出请求
+if ($is_export) {
+    $export_type = isset($_GET['type']) ? $_GET['type'] : '';
+    
+    switch ($export_type) {
+        case 'customers':
+            renderMonthlyDealCustomersTable($monthly_deal_customers, true);
+            break;
+        case 'employee':
+            renderDealStatsByEmployeeTable($deal_stats_by_employee, true);
+            break;
+    }
+    
+    exit; // 确保导出后停止执行
+}
+
+?>
+
+<div class="container">
+    <div class="page-header">
+        <h1 class="page-title">每月新增成交客户统计</h1>
+    </div>
+    
+    <!-- 日期筛选 -->
+    <div class="filter-form mb-5">
+        <form method="get" class="filter-form-inline">
+            <div class="form-group mr-3">
+                <label for="date_range" class="mr-2">选择日期范围</label>
+                <select class="form-control" id="date_range" name="date_range" onchange="toggleCustomDates()">
+                    <option value="current_month" <?php echo $date_range == 'current_month' ? 'selected' : ''; ?>>本月</option>
+                    <option value="last_month" <?php echo $date_range == 'last_month' ? 'selected' : ''; ?>>上月</option>
+                    <option value="current_year" <?php echo $date_range == 'current_year' ? 'selected' : ''; ?>>今年</option>
+                    <option value="last_30_days" <?php echo $date_range == 'last_30_days' ? 'selected' : ''; ?>>最近30天</option>
+                    <option value="last_90_days" <?php echo $date_range == 'last_90_days' ? 'selected' : ''; ?>>最近90天</option>
+                    <option value="custom" <?php echo $date_range == 'custom' ? 'selected' : ''; ?>>自定义日期范围</option>
+                </select>
+            </div>
+            <div class="form-group custom-date-inputs mr-3" id="custom_start_date" style="display: <?php echo $date_range == 'custom' ? 'inline-block' : 'none'; ?>">
+                <label for="start_date" class="mr-2">开始日期</label>
+                <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo $date_params['custom_start']; ?>">
+            </div>
+            <div class="form-group custom-date-inputs mr-3" id="custom_end_date" style="display: <?php echo $date_range == 'custom' ? 'inline-block' : 'none'; ?>">
+                <label for="end_date" class="mr-2">结束日期</label>
+                <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo $date_params['custom_end']; ?>">
+            </div>
+            
+            <!-- 业务员选择 -->
+            <div class="form-group mr-3">
+                <label for="selected_employee" class="mr-2">选择业务员</label>
+                <select class="form-control" id="selected_employee" name="selected_employee">
+                    <option value="all">所有业务员</option>
+                    <?php
+                    // 获取当前用户可见的业务员列表
+                    $visible_employees_query = "";
+                    
+                    if ($current_permission_role == 1) {
+                        // 管理员可以看到所有业务员
+                        $visible_employees_query = "SELECT id, em_user FROM employee WHERE em_role IS NOT NULL ORDER BY em_user";
+                    } elseif ($current_permission_role == 2) {
+                        // 组长可以看到自己和组员
+                        $visible_employees_query = "SELECT id, em_user FROM employee WHERE id = $current_employee_id OR em_role = $current_employee_id ORDER BY em_user";
+                    } else {
+                        // 组员只能看到自己
+                        $visible_employees_query = "SELECT id, em_user FROM employee WHERE id = $current_employee_id";
+                    }
+                    
+                    $visible_employees_result = $conn->query($visible_employees_query);
+                    $selected_employee = isset($_GET['selected_employee']) ? $_GET['selected_employee'] : 'all';
+                    
+                    while ($emp = $visible_employees_result->fetch_assoc()) {
+                        $selected = ($selected_employee == $emp['id']) ? 'selected' : '';
+                        echo "<option value='".$emp['id']."' $selected>".$emp['em_user']."</option>";
+                    }
+                    ?>
+                </select>
+            </div>
+            
+            <div class="form-group">
+                <button type="submit" class="btn btn-primary">应用筛选</button>
+            </div>
+        </form>
+    </div>
+    
+    <!-- 统计内容区域 -->
+    <div class="stats-content">
+        <?php
+        // 渲染表格
+        renderMonthlyDealCustomersTable($monthly_deal_customers);
+        renderDealStatsByEmployeeTable($deal_stats_by_employee);
+        ?>
+    </div>
+</div>
+
+<style>
+/* 添加一些额外的样式以改善表格显示 */
+.filter-form {
+    background-color: #f8f9fa;
+    padding: 20px;
+    border-radius: 5px;
+    margin-bottom: 30px;
+}
+
+.filter-form-inline {
+    display: flex;
+    flex-wrap: wrap;
+    align-items: flex-end;
+}
+
+.filter-form .form-group {
+    margin-bottom: 10px;
+    margin-right: 15px;
+}
+
+/* 表格样式 */
+.table {
+    width: 100%;
+    margin-bottom: 1rem;
+}
+
+.table th, .table td {
+    padding: 12px;
+    vertical-align: middle;
+}
+
+/* 确保表头也是左对齐 */
+.thead-light th {
+    background-color: #f8f9fa;
+    border-color: #dee2e6;
+    text-align: left;
+}
+
+.table-striped tbody tr:nth-of-type(odd) {
+    background-color: rgba(0, 0, 0, 0.03);
+}
+
+.card {
+    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
+}
+
+.card-header {
+    background-color: #f8f9fa;
+    padding: 15px;
+}
+
+.card-body {
+    padding: 1.5rem;
+}
+
+/* 添加按钮左边距 */
+.ml-3 {
+    margin-left: 15px !important;
+}
+
+/* 确保卡片头部布局正确 */
+.card-header.d-flex {
+    display: flex !important;
+    justify-content: space-between !important;
+    align-items: center !important;
+}
+</style>
+
+<script>
+function toggleCustomDates() {
+    const dateRange = document.getElementById('date_range').value;
+    const customDateInputs = document.querySelectorAll('.custom-date-inputs');
+    
+    if (dateRange === 'custom') {
+        customDateInputs.forEach(el => el.style.display = 'inline-block');
+    } else {
+        customDateInputs.forEach(el => el.style.display = 'none');
+    }
+}
+</script>
+
+<?php
+// 页面底部
+include('statistics_footer.php');
+?> 

+ 4 - 0
panel.php

@@ -83,6 +83,10 @@ $stmt->close();
                     <a href="region_stats.php" target="contentFrame">地区统计分析</a>
 <!--                    <a href="sales_stats.php" target="contentFrame">销售统计分析</a>-->
                     <a href="statistics_order_warnings.php" target="contentFrame">订单预警系统</a>
+                    <a href="monthly_deal_stats.php" target="contentFrame">每月新成交客户</a>
+                    <a href="region_performance_stats.php" target="contentFrame">每月区域新客户业绩</a>
+                    <a href="inquiry_conversion_stats.php" target="contentFrame">客户来源转化率</a>
+                    <a href="customer_composition_stats.php" target="contentFrame">每月业绩客户构成</a>
 
                 </div>
 

+ 538 - 0
region_performance_stats.php

@@ -0,0 +1,538 @@
+<?php
+/**
+ * 每月新区域客户总业绩统计分析
+ */
+require_once 'conn.php';
+require_once 'statistics_utils.php';
+require_once 'statistics_customers.php';
+require_once 'statistics_sales.php';
+// 检查登录状态
+if (!isset($_SESSION['employee_id'])) {
+    checkLogin();
+}
+
+function formatCurrency($value) {
+    return '¥' . number_format($value ?? 0, 2);
+}
+
+// 获取当前登录用户信息
+$current_employee_id = $_SESSION['employee_id'];
+$current_permission_role = 0;
+
+// 获取当前用户权限角色
+$current_employee_id = intval($current_employee_id); // 确保是整数
+$query = "SELECT em_permission_role_id FROM employee WHERE id = $current_employee_id";
+$result = $conn->query($query);
+if ($result && $row = $result->fetch_assoc()) {
+    $current_permission_role = $row['em_permission_role_id'];
+}
+
+// 检查是否为导出请求
+$is_export = isset($_GET['export']) && $_GET['export'] == 'excel';
+
+// 获取日期范围参数
+$date_params = getDateRangeParams();
+$start_date = $date_params['start_date_sql'];
+$end_date = $date_params['end_date_sql'];
+$date_range = $date_params['date_range'];
+$period = $date_params['period'];
+
+// 如果不是导出操作,则包含页面头部
+if (!$is_export) {
+    include('statistics_header.php');
+}
+
+/**
+ * 获取每月各区域新增客户业绩数据
+ */
+function getMonthlyRegionPerformance($conn, $start_date, $end_date, $employee_filter = null) {
+    $sql = "SELECT 
+                DATE_FORMAT(o.order_date, '%Y-%m') AS month,
+                co.countryName AS region,
+                COUNT(DISTINCT c.id) AS customer_count,
+                SUM(o.total_amount) AS total_amount
+            FROM orders o
+            JOIN customer c ON o.customer_id = c.id
+            JOIN country co ON c.cs_country = co.id
+            WHERE o.order_date BETWEEN '$start_date' AND '$end_date'
+            AND c.cs_deal = 3
+            AND c.cs_dealdate BETWEEN '$start_date' AND '$end_date'";
+    
+    // 根据员工过滤条件添加WHERE子句
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (!empty($employee_filter)) {
+                $employee_ids = implode(',', array_map('intval', $employee_filter));
+                $sql .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql .= " AND c.cs_belong = " . intval($employee_filter);
+        }
+    }
+    
+    $sql .= " GROUP BY DATE_FORMAT(o.order_date, '%Y-%m'), co.id
+              ORDER BY month, total_amount DESC";
+    
+    $result = $conn->query($sql);
+    $data = [];
+    
+    if ($result) {
+        while ($row = $result->fetch_assoc()) {
+            $data[] = $row;
+        }
+    }
+    
+    return $data;
+}
+
+/**
+ * 获取区域业绩汇总数据
+ */
+function getRegionPerformanceSummary($conn, $start_date, $end_date, $employee_filter = null) {
+    $sql = "SELECT 
+                co.countryName AS region,
+                COUNT(DISTINCT c.id) AS customer_count,
+                SUM(o.total_amount) AS total_amount
+            FROM orders o
+            JOIN customer c ON o.customer_id = c.id
+            JOIN country co ON c.cs_country = co.id
+            WHERE o.order_date BETWEEN '$start_date' AND '$end_date'
+            AND c.cs_deal = 3
+            AND c.cs_dealdate BETWEEN '$start_date' AND '$end_date'";
+    
+    // 根据员工过滤条件添加WHERE子句
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (!empty($employee_filter)) {
+                $employee_ids = implode(',', array_map('intval', $employee_filter));
+                $sql .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql .= " AND c.cs_belong = " . intval($employee_filter);
+        }
+    }
+    
+    $sql .= " GROUP BY co.id
+              ORDER BY total_amount DESC";
+    
+    $result = $conn->query($sql);
+    $data = [];
+    
+    if ($result) {
+        while ($row = $result->fetch_assoc()) {
+            $data[] = $row;
+        }
+    }
+    
+    return $data;
+}
+
+/**
+ * 导出数据为CSV
+ */
+function exportToCSV($data, $columns, $filename) {
+    // 设置头信息
+    header('Content-Type: text/csv; charset=utf-8');
+    header('Content-Disposition: attachment;filename="' . $filename . '.csv"');
+    header('Cache-Control: max-age=0');
+    
+    // 创建输出流
+    $output = fopen('php://output', 'w');
+    
+    // 添加UTF-8 BOM以确保Excel正确显示中文
+    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
+    
+    // 输出列头
+    fputcsv($output, $columns);
+    
+    // 输出数据行
+    foreach ($data as $row) {
+        // 确保所有数据都是数组格式
+        $rowData = array_values($row);
+        fputcsv($output, $rowData);
+    }
+    
+    fclose($output);
+    exit;
+}
+
+/**
+ * 渲染每月区域业绩表格
+ */
+function renderMonthlyRegionPerformanceTable($data, $is_export = false) {
+    if (empty($data)) {
+        if (!$is_export) {
+            echo '<div class="alert alert-info">当前选择范围内没有区域业绩数据</div>';
+        }
+        return;
+    }
+    
+    // 准备数据
+    $table_data = [];
+    $total_amount = 0;
+    $total_customers = 0;
+    
+    // 按月份分组整理数据
+    $months_data = [];
+    foreach ($data as $item) {
+        $months_data[$item['month']][] = $item;
+        $total_amount += floatval($item['total_amount']);
+        $total_customers += intval($item['customer_count']);
+    }
+    
+    foreach ($months_data as $month => $regions) {
+        foreach ($regions as $region) {
+            $table_data[] = [
+                '月份' => $month,
+                '区域' => $region['region'],
+                '新成交客户数' => $region['customer_count'],
+                '成交金额' => $is_export ? $region['total_amount'] : formatCurrency($region['total_amount'])
+            ];
+        }
+    }
+    
+    // 如果是导出请求,则导出数据
+    if ($is_export) {
+        exportToCSV(
+            $table_data, 
+            ['月份', '区域', '新成交客户数', '成交金额'], 
+            '每月区域新客户业绩_' . date('Ymd')
+        );
+        return;
+    }
+    
+    // 渲染表格
+    echo '<div class="row mt-5 mb-5">';
+    echo '<div class="col-md-12">';
+    echo '<div class="card">';
+    echo '<div class="card-header d-flex justify-content-between align-items-center">';
+    echo '<span>每月区域新客户业绩明细 (总计: '.formatCurrency($total_amount).', 共'.$total_customers.'个新客户)</span>';
+    echo '<a href="' . $_SERVER['REQUEST_URI'] . '&export=excel&type=monthly" class="btn btn-sm btn-success ml-3">导出CSV</a>';
+    echo '</div>';
+    echo '<div class="card-body">';
+    echo '<div class="table-responsive">';
+    echo '<table class="table table-bordered table-striped">';
+    echo '<thead class="thead-light">';
+    echo '<tr>';
+    echo '<th style="width: 15%; text-align: left;">月份</th>';
+    echo '<th style="width: 30%; text-align: left;">区域</th>';
+    echo '<th style="width: 25%; text-align: left;">新成交客户数</th>';
+    echo '<th style="width: 30%; text-align: left;">成交金额</th>';
+    echo '</tr>';
+    echo '</thead>';
+    echo '<tbody>';
+    
+    $current_month = '';
+    foreach ($months_data as $month => $regions) {
+        foreach ($regions as $index => $region) {
+            echo '<tr>';
+            // 只在每个月份的第一行显示月份
+            if ($index === 0) {
+                echo '<td rowspan="' . count($regions) . '">' . $month . '</td>';
+            }
+            echo '<td>' . $region['region'] . '</td>';
+            echo '<td>' . $region['customer_count'] . '</td>';
+            echo '<td>' . formatCurrency($region['total_amount']) . '</td>';
+            echo '</tr>';
+        }
+    }
+    
+    echo '</tbody>';
+    echo '</table>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+}
+
+/**
+ * 渲染区域业绩汇总表格
+ */
+function renderRegionPerformanceSummaryTable($data, $is_export = false) {
+    if (empty($data)) {
+        if (!$is_export) {
+            echo '<div class="alert alert-info">当前选择范围内没有区域业绩汇总数据</div>';
+        }
+        return;
+    }
+    
+    // 准备数据
+    $table_data = [];
+    $total_amount = 0;
+    $total_customers = 0;
+    
+    foreach ($data as $item) {
+        $table_data[] = [
+            '区域' => $item['region'],
+            '新成交客户数' => $item['customer_count'],
+            '成交金额' => $is_export ? $item['total_amount'] : formatCurrency($item['total_amount'])
+        ];
+        $total_amount += floatval($item['total_amount']);
+        $total_customers += intval($item['customer_count']);
+    }
+    
+    // 如果是导出请求,则导出数据
+    if ($is_export) {
+        exportToCSV(
+            $table_data, 
+            ['区域', '新成交客户数', '成交金额'],
+            '区域新客户业绩汇总_' . date('Ymd')
+        );
+        return;
+    }
+    
+    // 渲染表格
+    echo '<div class="row mt-5">';
+    echo '<div class="col-md-12">';
+    echo '<div class="card">';
+    echo '<div class="card-header d-flex justify-content-between align-items-center">';
+    echo '<span>区域新客户业绩汇总 (总计: '.formatCurrency($total_amount).', 共'.$total_customers.'个新客户)</span>';
+    echo '<a href="' . $_SERVER['REQUEST_URI'] . '&export=excel&type=summary" class="btn btn-sm btn-success ml-3">导出CSV</a>';
+    echo '</div>';
+    echo '<div class="card-body">';
+    echo '<div class="table-responsive">';
+    echo '<table class="table table-bordered table-striped">';
+    echo '<thead class="thead-light">';
+    echo '<tr>';
+    echo '<th style="width: 40%; text-align: left;">区域</th>';
+    echo '<th style="width: 30%; text-align: left;">新成交客户数</th>';
+    echo '<th style="width: 30%; text-align: left;">成交金额</th>';
+    echo '</tr>';
+    echo '</thead>';
+    echo '<tbody>';
+    
+    foreach ($data as $item) {
+        echo '<tr>';
+        echo '<td>' . $item['region'] . '</td>';
+        echo '<td>' . $item['customer_count'] . '</td>';
+        echo '<td>' . formatCurrency($item['total_amount']) . '</td>';
+        echo '</tr>';
+    }
+    
+    echo '</tbody>';
+    echo '</table>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+    echo '</div>';
+}
+
+// 获取选择的业务员
+$selected_employee = isset($_GET['selected_employee']) ? $_GET['selected_employee'] : 'all';
+
+// 确定要显示哪些业务员的数据
+$employee_filter = null;
+
+if ($selected_employee != 'all') {
+    // 如果选择了特定业务员,则只显示该业务员的数据
+    $employee_filter = intval($selected_employee);
+} else {
+    // 否则按权限显示相应的业务员数据
+    if ($current_permission_role == 1) {
+        // 管理员可以看到所有业务员
+        $employee_filter = null;
+    } elseif ($current_permission_role == 2) {
+        // 组长可以看到自己和组员
+        $visible_employees = [];
+        $query = "SELECT id FROM employee WHERE id = " . intval($current_employee_id) . " OR em_role = " . intval($current_employee_id);
+        $result = $conn->query($query);
+        
+        if ($result) {
+            while ($row = $result->fetch_assoc()) {
+                $visible_employees[] = $row['id'];
+            }
+        }
+        
+        $employee_filter = $visible_employees;
+    } else {
+        // 组员只能看到自己
+        $employee_filter = intval($current_employee_id);
+    }
+}
+
+// 获取每月区域业绩数据
+$monthly_region_performance = getMonthlyRegionPerformance($conn, $start_date, $end_date, $employee_filter);
+
+// 获取区域业绩汇总数据
+$region_performance_summary = getRegionPerformanceSummary($conn, $start_date, $end_date, $employee_filter);
+
+// 处理导出请求
+if ($is_export) {
+    $export_type = isset($_GET['type']) ? $_GET['type'] : '';
+    
+    switch ($export_type) {
+        case 'monthly':
+            renderMonthlyRegionPerformanceTable($monthly_region_performance, true);
+            break;
+        case 'summary':
+            renderRegionPerformanceSummaryTable($region_performance_summary, true);
+            break;
+    }
+    
+    exit; // 确保导出后停止执行
+}
+
+?>
+
+<div class="container">
+    <div class="page-header">
+        <h1 class="page-title">每月区域新客户总业绩统计</h1>
+    </div>
+    
+    <!-- 日期筛选 -->
+    <div class="filter-form mb-5">
+        <form method="get" class="filter-form-inline">
+            <div class="form-group mr-3">
+                <label for="date_range" class="mr-2">选择日期范围</label>
+                <select class="form-control" id="date_range" name="date_range" onchange="toggleCustomDates()">
+                    <option value="current_month" <?php echo $date_range == 'current_month' ? 'selected' : ''; ?>>本月</option>
+                    <option value="last_month" <?php echo $date_range == 'last_month' ? 'selected' : ''; ?>>上月</option>
+                    <option value="current_year" <?php echo $date_range == 'current_year' ? 'selected' : ''; ?>>今年</option>
+                    <option value="last_30_days" <?php echo $date_range == 'last_30_days' ? 'selected' : ''; ?>>最近30天</option>
+                    <option value="last_90_days" <?php echo $date_range == 'last_90_days' ? 'selected' : ''; ?>>最近90天</option>
+                    <option value="custom" <?php echo $date_range == 'custom' ? 'selected' : ''; ?>>自定义日期范围</option>
+                </select>
+            </div>
+            <div class="form-group custom-date-inputs mr-3" id="custom_start_date" style="display: <?php echo $date_range == 'custom' ? 'inline-block' : 'none'; ?>">
+                <label for="start_date" class="mr-2">开始日期</label>
+                <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo $date_params['custom_start']; ?>">
+            </div>
+            <div class="form-group custom-date-inputs mr-3" id="custom_end_date" style="display: <?php echo $date_range == 'custom' ? 'inline-block' : 'none'; ?>">
+                <label for="end_date" class="mr-2">结束日期</label>
+                <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo $date_params['custom_end']; ?>">
+            </div>
+            
+            <!-- 业务员选择 -->
+            <div class="form-group mr-3">
+                <label for="selected_employee" class="mr-2">选择业务员</label>
+                <select class="form-control" id="selected_employee" name="selected_employee">
+                    <option value="all">所有业务员</option>
+                    <?php
+                    // 获取当前用户可见的业务员列表
+                    $visible_employees_query = "";
+                    
+                    if ($current_permission_role == 1) {
+                        // 管理员可以看到所有业务员
+                        $visible_employees_query = "SELECT id, em_user FROM employee WHERE em_role IS NOT NULL ORDER BY em_user";
+                    } elseif ($current_permission_role == 2) {
+                        // 组长可以看到自己和组员
+                        $visible_employees_query = "SELECT id, em_user FROM employee WHERE id = $current_employee_id OR em_role = $current_employee_id ORDER BY em_user";
+                    } else {
+                        // 组员只能看到自己
+                        $visible_employees_query = "SELECT id, em_user FROM employee WHERE id = $current_employee_id";
+                    }
+                    
+                    $visible_employees_result = $conn->query($visible_employees_query);
+                    $selected_employee = isset($_GET['selected_employee']) ? $_GET['selected_employee'] : 'all';
+                    
+                    while ($emp = $visible_employees_result->fetch_assoc()) {
+                        $selected = ($selected_employee == $emp['id']) ? 'selected' : '';
+                        echo "<option value='".$emp['id']."' $selected>".$emp['em_user']."</option>";
+                    }
+                    ?>
+                </select>
+            </div>
+            
+            <div class="form-group">
+                <button type="submit" class="btn btn-primary">应用筛选</button>
+            </div>
+        </form>
+    </div>
+    
+    <!-- 统计内容区域 -->
+    <div class="stats-content">
+        <?php
+        // 渲染表格
+        renderRegionPerformanceSummaryTable($region_performance_summary);
+        renderMonthlyRegionPerformanceTable($monthly_region_performance);
+        ?>
+    </div>
+</div>
+
+<style>
+/* 添加一些额外的样式以改善表格显示 */
+.filter-form {
+    background-color: #f8f9fa;
+    padding: 20px;
+    border-radius: 5px;
+    margin-bottom: 30px;
+}
+
+.filter-form-inline {
+    display: flex;
+    flex-wrap: wrap;
+    align-items: flex-end;
+}
+
+.filter-form .form-group {
+    margin-bottom: 10px;
+    margin-right: 15px;
+}
+
+/* 表格样式 */
+.table {
+    width: 100%;
+    margin-bottom: 1rem;
+}
+
+.table th, .table td {
+    padding: 12px;
+    vertical-align: middle;
+}
+
+/* 确保表头也是左对齐 */
+.thead-light th {
+    background-color: #f8f9fa;
+    border-color: #dee2e6;
+    text-align: left;
+}
+
+.table-striped tbody tr:nth-of-type(odd) {
+    background-color: rgba(0, 0, 0, 0.03);
+}
+
+.card {
+    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
+}
+
+.card-header {
+    background-color: #f8f9fa;
+    padding: 15px;
+}
+
+.card-body {
+    padding: 1.5rem;
+}
+
+/* 添加按钮左边距 */
+.ml-3 {
+    margin-left: 15px !important;
+}
+
+/* 确保卡片头部布局正确 */
+.card-header.d-flex {
+    display: flex !important;
+    justify-content: space-between !important;
+    align-items: center !important;
+}
+</style>
+
+<script>
+function toggleCustomDates() {
+    const dateRange = document.getElementById('date_range').value;
+    const customDateInputs = document.querySelectorAll('.custom-date-inputs');
+    
+    if (dateRange === 'custom') {
+        customDateInputs.forEach(el => el.style.display = 'inline-block');
+    } else {
+        customDateInputs.forEach(el => el.style.display = 'none');
+    }
+}
+</script>
+
+<?php
+// 页面底部
+include('statistics_footer.php');
+?>