浏览代码

fleat: update statistics

igb 1 周之前
父节点
当前提交
3e4ccf8e85
共有 14 个文件被更改,包括 2440 次插入1164 次删除
  1. 399 398
      customers.php
  2. 7 7
      customersFollow.php
  3. 141 135
      customersNew.php
  4. 149 7
      customers_stats.php
  5. 85 16
      products_stats.php
  6. 85 16
      region_stats.php
  7. 202 45
      statistics_customers.php
  8. 245 31
      statistics_order_warnings.php
  9. 415 110
      statistics_products.php
  10. 266 13
      statistics_region.php
  11. 150 98
      statistics_utils.php
  12. 199 183
      subCustomers.php
  13. 82 105
      subTag.php
  14. 15 0
      subTagClound.php

+ 399 - 398
customers.php

@@ -10,397 +10,398 @@ checkLogin();
 $act = $_GET['act'] ?? '';
 $urlStr = '';
 
-// 处理保存操作
-if ($act == "save") {
-    $isedit = false;
-    $id = $_POST['id'] ?? '';
-    if (!empty($id) && is_numeric($id)) {
-        $isedit = true;
-    }
-    
-    // 获取表单数据 - 客户基本信息
-    $cs_code = textEncode($_POST['cs_code']);
-    $cs_company = textEncode($_POST['cs_company']);
-    $cs_belong = $_POST['cs_belong'];
-    $cs_country = $_POST['cs_country'];
-    $cs_from = $_POST['cs_from'];
-    $cs_state = $_POST['cs_state'];
-    $cs_deal = $_POST['cs_deal'];
-    $cs_type = $_POST['cs_type'] ?? 5;
-    $cs_belongclient = $_POST['cs_belongclient'] ?? 0;
-    $no_content = htmlEncode($_POST['no_content']);
-    $allowedit = isset($_POST['allowedit']) ? 1 : 0;
-    $cs_address = textEncode($_POST['cs_address'] ?? '');
-    $mytag = textEncode($_POST['mytag'] ?? '');
-    $mytag = str_replace(['</span><span>', '</span>', '<span>'], [',', '', ''], $mytag);
-    $mytag = explode(',', $mytag);
-
-    // 获取联系人信息
-    $contacts = $_POST['contact'] ?? [];
-
-    // 验证必填字段
-    if (empty($cs_code)) {
-        echo "<script>alert('客户编码不能为空');history.back();</script>";
-        exit;
-    }
-
-    if ($cs_country == 0) {
-        echo "<script>alert('这是哪个国家的客户?');history.back();</script>";
-        exit;
-    }
-
-    if ($cs_from == "0") {
-        echo "<script>alert('请填写客户来源!');history.back();</script>";
-        exit;
-    }
-
-    // 自动检测来源
-    if (strpos($cs_code, ';1688') !== false) {
-        $cs_from = 1; // 1688
-    }
-    if (strpos($cs_code, ';阿里') !== false) {
-        $cs_from = 2; // International station
-    }
-    if (strpos($cs_code, '官网') !== false) {
-        $cs_from = 3; // Website
-    }
-
-    // 验证联系方式
-    $primary_contact = !empty($contacts) ? current($contacts) : [];
-    
-    if ($allowedit != 1) {
-        // 阿里巴巴验证
-        if (($cs_from == 1 || $cs_from == 2) && empty($primary_contact['alibaba_1'])) {
-            echo "<script>alert('阿里旺旺为必填项');history.back();</script>";
-            exit;
-        }
-
-        // 官网来源验证
-        if ($cs_from == 3) {
-            $has_required = false;
-            for ($i = 1; $i <= 3; $i++) {
-                if (!empty($primary_contact['tel_' . $i]) || 
-                    !empty($primary_contact['whatsapp_' . $i]) || 
-                    !empty($primary_contact['wechat_' . $i])) {
-                    $has_required = true;
-                    break;
-                }
-            }
-            if (!$has_required) {
-                echo "<script>alert('电话和WhatsApp为必填项');history.back();</script>";
-                exit;
-            }
-        }
-
-        // 市场客户验证
-        if ($cs_from == 8) {
-            $has_wechat = false;
-            for ($i = 1; $i <= 3; $i++) {
-                if (!empty($primary_contact['wechat_' . $i])) {
-                    $has_wechat = true;
-                    break;
-                }
-            }
-            if (!$has_wechat) {
-                echo "<script>alert('微信为必填项');history.back();</script>";
-                exit;
-            }
-        }
-
-        // Facebook验证
-        if ($cs_from == 12) {
-            $has_facebook = false;
-            for ($i = 1; $i <= 3; $i++) {
-                if (!empty($primary_contact['facebook_' . $i])) {
-                    $has_facebook = true;
-                    break;
-                }
-            }
-            if (!$has_facebook) {
-                echo "<script>alert('Facebook为必填项');history.back();</script>";
-                exit;
-            }
-        }
-    }
-
-    if ($isedit) {
-        // 验证客户所有权
-        $sql = "SELECT cs_chain FROM customer WHERE id = $id";
-        $result = mysqli_query($conn, $sql);
-        if ($row = mysqli_fetch_assoc($result)) {
-            $cs_chain = $row['cs_chain'];
-            $chain_array = explode(',', $cs_chain);
-            $last_item = end($chain_array);
-            
-            if ($last_item != $cs_belong) {
-                $cs_chain .= ",$cs_belong";
-            }
-            
-            // 更新客户基本信息
-            $sql = "UPDATE customer SET 
-                    cs_code = '$cs_code',
-                    cs_company = '$cs_company',
-                    cs_belong = '$cs_belong',
-                    cs_country = '$cs_country',
-                    cs_address = '$cs_address',
-                    cs_from = '$cs_from',
-                    cs_state = '$cs_state',
-                    cs_deal = '$cs_deal',
-                    cs_type = '$cs_type',
-                    cs_belongclient = '$cs_belongclient',
-                    cs_note = '$no_content',
-                    allowedit = $allowedit,
-                    cs_chain = '$cs_chain',
-                    cs_updatetime = NOW()";
-
-            // 处理cs_dealdate
-            if ($cs_deal == 3) {
-                $sql .= ", cs_dealdate = CASE WHEN cs_dealdate IS NULL THEN NOW() ELSE cs_dealdate END";
-            }
-            
-            $sql .= " WHERE id = $id";
-            mysqli_query($conn, $sql);
-            
-            // 处理联系人信息
-            $existingContactIds = [];
-            foreach ($contacts as $contact) {
-                if (!empty($contact['id'])) {
-                    $existingContactIds[] = (int)$contact['id'];
-                }
-            }
-            
-            // 删除不再使用的联系人记录
-            if (!empty($existingContactIds)) {
-                $idsToKeep = implode(',', $existingContactIds);
-                $deleteContactsSql = "DELETE FROM customer_contact WHERE customer_id = $id AND id NOT IN ($idsToKeep)";
-            } else {
-                $deleteContactsSql = "DELETE FROM customer_contact WHERE customer_id = $id";
-            }
-            mysqli_query($conn, $deleteContactsSql);
-            
-            // 更新或添加联系人信息
-            foreach ($contacts as $contact) {
-                $contact_id = !empty($contact['id']) ? (int)$contact['id'] : 0;
-                $contact_name = textEncode($contact['contact_name'] ?? '');
-                
-                // 准备SQL字段和值
-                $fields = ['contact_name'];
-                $values = ["'" . mysqli_real_escape_string($conn, $contact_name) . "'"];
-                $updates = ["contact_name = '" . mysqli_real_escape_string($conn, $contact_name) . "'"];
-                
-                // 处理所有联系方式类型
-                $methodTypes = ['tel', 'email', 'whatsapp', 'wechat', 'linkedin', 'facebook', 'alibaba'];
-                foreach ($methodTypes as $type) {
-                    for ($i = 1; $i <= 3; $i++) {
-                        $field = $type . '_' . $i;
-                        $format_field = $field . '_format';
-                        $bu_field = $field . '_bu';
-                        
-                        $value = textEncode($contact[$field] ?? '');
-                        $format_value = ($type == 'tel' || $type == 'whatsapp') ? numFormat($value) : '';
-                        $bu_value = textEncode($contact[$bu_field] ?? $value);
-                        
-                        // 添加字段名
-                        $fields[] = $field;
-                        $fields[] = $bu_field;
-                        if ($type == 'tel' || $type == 'whatsapp') {
-                            $fields[] = $format_field;
-                        }
-                        
-                        // 添加值
-                        $values[] = "'" . mysqli_real_escape_string($conn, $value) . "'";
-                        $values[] = "'" . mysqli_real_escape_string($conn, $bu_value) . "'";
-                        if ($type == 'tel' || $type == 'whatsapp') {
-                            $values[] = "'" . mysqli_real_escape_string($conn, $format_value) . "'";
-                        }
-                        
-                        // 添加更新语句
-                        $updates[] = $field . " = '" . mysqli_real_escape_string($conn, $value) . "'";
-                        $updates[] = $bu_field . " = '" . mysqli_real_escape_string($conn, $bu_value) . "'";
-                        if ($type == 'tel' || $type == 'whatsapp') {
-                            $updates[] = $format_field . " = '" . mysqli_real_escape_string($conn, $format_value) . "'";
-                        }
-                    }
-                }
-                
-                if ($contact_id > 0) {
-                    // 更新已有联系人
-                    $updateContactSql = "UPDATE customer_contact SET " .
-                        implode(", ", $updates) . ", updated_at = NOW() " .
-                        "WHERE id = $contact_id AND customer_id = $id";
-                    mysqli_query($conn, $updateContactSql);
-                } else {
-                    // 添加新联系人
-                    $insertContactSql = "INSERT INTO customer_contact (" .
-                        implode(", ", $fields) . ", customer_id, created_at, updated_at) VALUES (" .
-                        implode(", ", $values) . ", $id, NOW(), NOW())";
-                    mysqli_query($conn, $insertContactSql);
-                }
-            }
-
-            // 更新标签
-            mysqli_query($conn, "DELETE FROM tagtable WHERE customerId = $id");
-            foreach ($mytag as $tag) {
-                if (!empty(trim($tag))) {
-                    $tagSql = "INSERT INTO tagtable (tagName, employeeId, customerId) VALUES ('" . 
-                             mysqli_real_escape_string($conn, $tag) . "', " . 
-                             $_SESSION['employee_id'] . ", $id)";
-                    mysqli_query($conn, $tagSql);
-                }
-            }
-            
-            $page = $_GET['Page'] ?? '';
-            $keys = urlencode($_GET['Keys'] ?? '');
-            header("Location: ?keys=$keys&Page=$page$urlStr");
-            exit;
-        }
-    } else {
-        // 创建新记录
-        // 插入客户基本信息
-        $sql = "INSERT INTO customer (
-                cs_code, cs_company, cs_country, cs_address, cs_from, 
-                cs_belong, cs_state, cs_deal, cs_type, cs_belongclient,
-                cs_note, allowedit, cs_chain, cs_addtime, cs_updatetime,
-                is_silent, cs_dealdate
-            ) VALUES (
-                '$cs_code', '$cs_company', '$cs_country', '$cs_address', '$cs_from',
-                '$cs_belong', '$cs_state', '$cs_deal', '$cs_type', '$cs_belongclient',
-                '$no_content', $allowedit, '$cs_belong', NOW(), NOW(),
-                0, " . ($cs_deal == 3 ? "NOW()" : "NULL") . "
-            )";
-        mysqli_query($conn, $sql);
-        $new_customer_id = mysqli_insert_id($conn);
-        
-        // 插入联系人信息
-        if ($new_customer_id > 0) {
-            foreach ($contacts as $contact) {
-                $contact_name = textEncode($contact['contact_name'] ?? '');
-                
-                // 准备SQL字段和值
-                $fields = ['contact_name'];
-                $values = ["'" . mysqli_real_escape_string($conn, $contact_name) . "'"];
-                
-                // 处理所有联系方式类型
-                $methodTypes = ['tel', 'email', 'whatsapp', 'wechat', 'linkedin', 'facebook', 'alibaba'];
-                foreach ($methodTypes as $type) {
-                    for ($i = 1; $i <= 3; $i++) {
-                        $field = $type . '_' . $i;
-                        $format_field = $field . '_format';
-                        $bu_field = $field . '_bu';
-                        
-                        $value = textEncode($contact[$field] ?? '');
-                        $format_value = ($type == 'tel' || $type == 'whatsapp') ? numFormat($value) : '';
-                        $bu_value = textEncode($contact[$bu_field] ?? $value);
-                        
-                        // 添加字段名
-                        $fields[] = $field;
-                        $fields[] = $bu_field;
-                        if ($type == 'tel' || $type == 'whatsapp') {
-                            $fields[] = $format_field;
-                        }
-                        
-                        // 添加值
-                        $values[] = "'" . mysqli_real_escape_string($conn, $value) . "'";
-                        $values[] = "'" . mysqli_real_escape_string($conn, $bu_value) . "'";
-                        if ($type == 'tel' || $type == 'whatsapp') {
-                            $values[] = "'" . mysqli_real_escape_string($conn, $format_value) . "'";
-                        }
-                    }
-                }
-                
-                // 添加新联系人
-                $insertContactSql = "INSERT INTO customer_contact (" .
-                    implode(", ", $fields) . ", customer_id, created_at, updated_at) VALUES (" .
-                    implode(", ", $values) . ", $new_customer_id, NOW(), NOW())";
-                mysqli_query($conn, $insertContactSql);
-            }
-
-            // 保存标签
-            foreach ($mytag as $tag) {
-                if (!empty(trim($tag))) {
-                    $tagSql = "INSERT INTO tagtable (tagName, employeeId, customerId) VALUES ('" . 
-                             mysqli_real_escape_string($conn, $tag) . "', " . 
-                             $_SESSION['employee_id'] . ", $new_customer_id)";
-                    mysqli_query($conn, $tagSql);
-                }
-            }
-            
-            $page = $_GET['Page'] ?? '';
-            $keys = urlencode($_GET['Keys'] ?? '');
-            header("Location: ?keys=$keys&Page=$page$urlStr");
-            exit;
-        }
-    }
-}
-
-// 处理编辑操作
-if ($act == "edit") {
-    $id = $_GET['id'] ?? '';
-    $isedit = false;
-    if (!empty($id) && is_numeric($id)) {
-        $isedit = true;
-    }
-    
-    if ($isedit) {
-        // 联合查询客户基本信息和联系人信息
-        $sql = "SELECT c.*, 
-                cc.id as contact_id, cc.contact_name,
-                cc.tel_1, cc.tel_1_format, cc.tel_1_bu,
-                cc.tel_2, cc.tel_2_format, cc.tel_2_bu,
-                cc.tel_3, cc.tel_3_format, cc.tel_3_bu,
-                cc.email_1, cc.email_1_bu,
-                cc.email_2, cc.email_2_bu,
-                cc.email_3, cc.email_3_bu,
-                cc.whatsapp_1, cc.whatsapp_1_format, cc.whatsapp_1_bu,
-                cc.whatsapp_2, cc.whatsapp_2_format, cc.whatsapp_2_bu,
-                cc.whatsapp_3, cc.whatsapp_3_format, cc.whatsapp_3_bu,
-                cc.wechat_1, cc.wechat_1_bu,
-                cc.wechat_2, cc.wechat_2_bu,
-                cc.wechat_3, cc.wechat_3_bu,
-                cc.linkedin_1, cc.linkedin_1_bu,
-                cc.linkedin_2, cc.linkedin_2_bu,
-                cc.linkedin_3, cc.linkedin_3_bu,
-                cc.facebook_1, cc.facebook_1_bu,
-                cc.facebook_2, cc.facebook_2_bu,
-                cc.facebook_3, cc.facebook_3_bu,
-                cc.alibaba_1, cc.alibaba_1_bu,
-                cc.alibaba_2, cc.alibaba_2_bu,
-                cc.alibaba_3, cc.alibaba_3_bu
-                FROM customer c 
-                LEFT JOIN customer_contact cc ON c.id = cc.customer_id
-                WHERE c.id = $id";
-        $result = mysqli_query($conn, $sql);
-        if ($row = mysqli_fetch_assoc($result)) {
-            $cs_code = textDecode($row['cs_code']);
-            $cs_company = textDecode($row['cs_company']);
-            $cs_name = textDecode($row['contact_name']);
-            $cs_country = $row['cs_country'];
-            $cs_from = $row['cs_from'];
-            $cs_tel = textDecode($row['tel_1']);
-            $cs_telBu = textDecode($row['tel_1_bu']);
-            $cs_email = textDecode($row['email_1']);
-            $cs_emailBu = textDecode($row['email_1_bu']);
-            $cs_whatsapp = textDecode($row['whatsapp_1']);
-            $cs_whatsappBu = textDecode($row['whatsapp_1_bu']);
-            $cs_wechat = textDecode($row['wechat_1']);
-            $cs_wechatBu = textDecode($row['wechat_1_bu']);
-            $cs_linkedin = textDecode($row['linkedin_1']);
-            $cs_linkedinBu = textDecode($row['linkedin_1_bu']);
-            $cs_facebook = textDecode($row['facebook_1']);
-            $cs_facebookBu = textDecode($row['facebook_1_bu']);
-            $cs_alibaba = textDecode($row['alibaba_1']);
-            $cs_alibabaBu = textDecode($row['alibaba_1_bu']);
-            $cs_address = textDecode($row['cs_address']);
-            $cs_addtime = $row['cs_addtime'];
-            $cs_updatetime = $row['cs_updatetime'];
-            $cs_belong = $row['cs_belong'];
-            $cs_state = $row['cs_state'];
-            $cs_deal = $row['cs_deal'];
-            $cs_note = htmlDecode($row['cs_note']);
-            $allowedit = $row['allowedit'];
-        }
-    }
-}
+//
+//// 处理保存操作
+//if ($act == "save") {
+//    $isedit = false;
+//    $id = $_POST['id'] ?? '';
+//    if (!empty($id) && is_numeric($id)) {
+//        $isedit = true;
+//    }
+//
+//    // 获取表单数据 - 客户基本信息
+//    $cs_code = textEncode($_POST['cs_code']);
+//    $cs_company = textEncode($_POST['cs_company']);
+//    $cs_belong = $_POST['cs_belong'];
+//    $cs_country = $_POST['cs_country'];
+//    $cs_from = $_POST['cs_from'];
+//    $cs_state = $_POST['cs_state'];
+//    $cs_deal = $_POST['cs_deal'];
+//    $cs_type = $_POST['cs_type'] ?? 5;
+//    $cs_belongclient = $_POST['cs_belongclient'] ?? 0;
+//    $no_content = htmlEncode($_POST['no_content']);
+//    $allowedit = isset($_POST['allowedit']) ? 1 : 0;
+//    $cs_address = textEncode($_POST['cs_address'] ?? '');
+//    $mytag = textEncode($_POST['mytag'] ?? '');
+//    $mytag = str_replace(['&#60;&#47;span&#62;&#60;span&#62;', '&#60;&#47;span&#62;', '&#60;span&#62;'], [',', '', ''], $mytag);
+//    $mytag = explode(',', $mytag);
+//
+//    // 获取联系人信息
+//    $contacts = $_POST['contact'] ?? [];
+//
+//    // 验证必填字段
+//    if (empty($cs_code)) {
+//        echo "<script>alert('客户编码不能为空');history.back();</script>";
+//        exit;
+//    }
+//
+//    if ($cs_country == 0) {
+//        echo "<script>alert('这是哪个国家的客户?');history.back();</script>";
+//        exit;
+//    }
+//
+//    if ($cs_from == "0") {
+//        echo "<script>alert('请填写客户来源!');history.back();</script>";
+//        exit;
+//    }
+//
+//    // 自动检测来源
+//    if (strpos($cs_code, ';1688') !== false) {
+//        $cs_from = 1; // 1688
+//    }
+//    if (strpos($cs_code, ';阿里') !== false) {
+//        $cs_from = 2; // International station
+//    }
+//    if (strpos($cs_code, '官网') !== false) {
+//        $cs_from = 3; // Website
+//    }
+//
+//    // 验证联系方式
+//    $primary_contact = !empty($contacts) ? current($contacts) : [];
+//
+//    if ($allowedit != 1) {
+//        // 阿里巴巴验证
+//        if (($cs_from == 1 || $cs_from == 2) && empty($primary_contact['alibaba_1'])) {
+//            echo "<script>alert('阿里旺旺为必填项');history.back();</script>";
+//            exit;
+//        }
+//
+//        // 官网来源验证
+//        if ($cs_from == 3) {
+//            $has_required = false;
+//            for ($i = 1; $i <= 3; $i++) {
+//                if (!empty($primary_contact['tel_' . $i]) ||
+//                    !empty($primary_contact['whatsapp_' . $i]) ||
+//                    !empty($primary_contact['wechat_' . $i])) {
+//                    $has_required = true;
+//                    break;
+//                }
+//            }
+//            if (!$has_required) {
+//                echo "<script>alert('电话和WhatsApp为必填项');history.back();</script>";
+//                exit;
+//            }
+//        }
+//
+//        // 市场客户验证
+//        if ($cs_from == 8) {
+//            $has_wechat = false;
+//            for ($i = 1; $i <= 3; $i++) {
+//                if (!empty($primary_contact['wechat_' . $i])) {
+//                    $has_wechat = true;
+//                    break;
+//                }
+//            }
+//            if (!$has_wechat) {
+//                echo "<script>alert('微信为必填项');history.back();</script>";
+//                exit;
+//            }
+//        }
+//
+//        // Facebook验证
+//        if ($cs_from == 12) {
+//            $has_facebook = false;
+//            for ($i = 1; $i <= 3; $i++) {
+//                if (!empty($primary_contact['facebook_' . $i])) {
+//                    $has_facebook = true;
+//                    break;
+//                }
+//            }
+//            if (!$has_facebook) {
+//                echo "<script>alert('Facebook为必填项');history.back();</script>";
+//                exit;
+//            }
+//        }
+//    }
+//
+//    if ($isedit) {
+//        // 验证客户所有权
+//        $sql = "SELECT cs_chain FROM customer WHERE id = $id";
+//        $result = mysqli_query($conn, $sql);
+//        if ($row = mysqli_fetch_assoc($result)) {
+//            $cs_chain = $row['cs_chain'];
+//            $chain_array = explode(',', $cs_chain);
+//            $last_item = end($chain_array);
+//
+//            if ($last_item != $cs_belong) {
+//                $cs_chain .= ",$cs_belong";
+//            }
+//
+//            // 更新客户基本信息
+//            $sql = "UPDATE customer SET
+//                    cs_code = '$cs_code',
+//                    cs_company = '$cs_company',
+//                    cs_belong = '$cs_belong',
+//                    cs_country = '$cs_country',
+//                    cs_address = '$cs_address',
+//                    cs_from = '$cs_from',
+//                    cs_state = '$cs_state',
+//                    cs_deal = '$cs_deal',
+//                    cs_type = '$cs_type',
+//                    cs_belongclient = '$cs_belongclient',
+//                    cs_note = '$no_content',
+//                    allowedit = $allowedit,
+//                    cs_chain = '$cs_chain',
+//                    cs_updatetime = NOW()";
+//
+//            // 处理cs_dealdate
+//            if ($cs_deal == 3) {
+//                $sql .= ", cs_dealdate = CASE WHEN cs_dealdate IS NULL THEN NOW() ELSE cs_dealdate END";
+//            }
+//
+//            $sql .= " WHERE id = $id";
+//            mysqli_query($conn, $sql);
+//
+//            // 处理联系人信息
+//            $existingContactIds = [];
+//            foreach ($contacts as $contact) {
+//                if (!empty($contact['id'])) {
+//                    $existingContactIds[] = (int)$contact['id'];
+//                }
+//            }
+//
+//            // 删除不再使用的联系人记录
+//            if (!empty($existingContactIds)) {
+//                $idsToKeep = implode(',', $existingContactIds);
+//                $deleteContactsSql = "DELETE FROM customer_contact WHERE customer_id = $id AND id NOT IN ($idsToKeep)";
+//            } else {
+//                $deleteContactsSql = "DELETE FROM customer_contact WHERE customer_id = $id";
+//            }
+//            mysqli_query($conn, $deleteContactsSql);
+//
+//            // 更新或添加联系人信息
+//            foreach ($contacts as $contact) {
+//                $contact_id = !empty($contact['id']) ? (int)$contact['id'] : 0;
+//                $contact_name = textEncode($contact['contact_name'] ?? '');
+//
+//                // 准备SQL字段和值
+//                $fields = ['contact_name'];
+//                $values = ["'" . mysqli_real_escape_string($conn, $contact_name) . "'"];
+//                $updates = ["contact_name = '" . mysqli_real_escape_string($conn, $contact_name) . "'"];
+//
+//                // 处理所有联系方式类型
+//                $methodTypes = ['tel', 'email', 'whatsapp', 'wechat', 'linkedin', 'facebook', 'alibaba'];
+//                foreach ($methodTypes as $type) {
+//                    for ($i = 1; $i <= 3; $i++) {
+//                        $field = $type . '_' . $i;
+//                        $format_field = $field . '_format';
+//                        $bu_field = $field . '_bu';
+//
+//                        $value = textEncode($contact[$field] ?? '');
+//                        $format_value = ($type == 'tel' || $type == 'whatsapp') ? numFormat($value) : '';
+//                        $bu_value = textEncode($contact[$bu_field] ?? $value);
+//
+//                        // 添加字段名
+//                        $fields[] = $field;
+//                        $fields[] = $bu_field;
+//                        if ($type == 'tel' || $type == 'whatsapp') {
+//                            $fields[] = $format_field;
+//                        }
+//
+//                        // 添加值
+//                        $values[] = "'" . mysqli_real_escape_string($conn, $value) . "'";
+//                        $values[] = "'" . mysqli_real_escape_string($conn, $bu_value) . "'";
+//                        if ($type == 'tel' || $type == 'whatsapp') {
+//                            $values[] = "'" . mysqli_real_escape_string($conn, $format_value) . "'";
+//                        }
+//
+//                        // 添加更新语句
+//                        $updates[] = $field . " = '" . mysqli_real_escape_string($conn, $value) . "'";
+//                        $updates[] = $bu_field . " = '" . mysqli_real_escape_string($conn, $bu_value) . "'";
+//                        if ($type == 'tel' || $type == 'whatsapp') {
+//                            $updates[] = $format_field . " = '" . mysqli_real_escape_string($conn, $format_value) . "'";
+//                        }
+//                    }
+//                }
+//
+//                if ($contact_id > 0) {
+//                    // 更新已有联系人
+//                    $updateContactSql = "UPDATE customer_contact SET " .
+//                        implode(", ", $updates) . ", updated_at = NOW() " .
+//                        "WHERE id = $contact_id AND customer_id = $id";
+//                    mysqli_query($conn, $updateContactSql);
+//                } else {
+//                    // 添加新联系人
+//                    $insertContactSql = "INSERT INTO customer_contact (" .
+//                        implode(", ", $fields) . ", customer_id, created_at, updated_at) VALUES (" .
+//                        implode(", ", $values) . ", $id, NOW(), NOW())";
+//                    mysqli_query($conn, $insertContactSql);
+//                }
+//            }
+//
+//            // 更新标签
+//            mysqli_query($conn, "DELETE FROM tagtable WHERE customerId = $id");
+//            foreach ($mytag as $tag) {
+//                if (!empty(trim($tag))) {
+//                    $tagSql = "INSERT INTO tagtable (tagName, employeeId, customerId) VALUES ('" .
+//                             mysqli_real_escape_string($conn, $tag) . "', " .
+//                             $_SESSION['employee_id'] . ", $id)";
+//                    mysqli_query($conn, $tagSql);
+//                }
+//            }
+//
+//            $page = $_GET['Page'] ?? '';
+//            $keys = urlencode($_GET['Keys'] ?? '');
+//            header("Location: ?keys=$keys&Page=$page$urlStr");
+//            exit;
+//        }
+//    } else {
+//        // 创建新记录
+//        // 插入客户基本信息
+//        $sql = "INSERT INTO customer (
+//                cs_code, cs_company, cs_country, cs_address, cs_from,
+//                cs_belong, cs_state, cs_deal, cs_type, cs_belongclient,
+//                cs_note, allowedit, cs_chain, cs_addtime, cs_updatetime,
+//                is_silent, cs_dealdate
+//            ) VALUES (
+//                '$cs_code', '$cs_company', '$cs_country', '$cs_address', '$cs_from',
+//                '$cs_belong', '$cs_state', '$cs_deal', '$cs_type', '$cs_belongclient',
+//                '$no_content', $allowedit, '$cs_belong', NOW(), NOW(),
+//                0, " . ($cs_deal == 3 ? "NOW()" : "NULL") . "
+//            )";
+//        mysqli_query($conn, $sql);
+//        $new_customer_id = mysqli_insert_id($conn);
+//
+//        // 插入联系人信息
+//        if ($new_customer_id > 0) {
+//            foreach ($contacts as $contact) {
+//                $contact_name = textEncode($contact['contact_name'] ?? '');
+//
+//                // 准备SQL字段和值
+//                $fields = ['contact_name'];
+//                $values = ["'" . mysqli_real_escape_string($conn, $contact_name) . "'"];
+//
+//                // 处理所有联系方式类型
+//                $methodTypes = ['tel', 'email', 'whatsapp', 'wechat', 'linkedin', 'facebook', 'alibaba'];
+//                foreach ($methodTypes as $type) {
+//                    for ($i = 1; $i <= 3; $i++) {
+//                        $field = $type . '_' . $i;
+//                        $format_field = $field . '_format';
+//                        $bu_field = $field . '_bu';
+//
+//                        $value = textEncode($contact[$field] ?? '');
+//                        $format_value = ($type == 'tel' || $type == 'whatsapp') ? numFormat($value) : '';
+//                        $bu_value = textEncode($contact[$bu_field] ?? $value);
+//
+//                        // 添加字段名
+//                        $fields[] = $field;
+//                        $fields[] = $bu_field;
+//                        if ($type == 'tel' || $type == 'whatsapp') {
+//                            $fields[] = $format_field;
+//                        }
+//
+//                        // 添加值
+//                        $values[] = "'" . mysqli_real_escape_string($conn, $value) . "'";
+//                        $values[] = "'" . mysqli_real_escape_string($conn, $bu_value) . "'";
+//                        if ($type == 'tel' || $type == 'whatsapp') {
+//                            $values[] = "'" . mysqli_real_escape_string($conn, $format_value) . "'";
+//                        }
+//                    }
+//                }
+//
+//                // 添加新联系人
+//                $insertContactSql = "INSERT INTO customer_contact (" .
+//                    implode(", ", $fields) . ", customer_id, created_at, updated_at) VALUES (" .
+//                    implode(", ", $values) . ", $new_customer_id, NOW(), NOW())";
+//                mysqli_query($conn, $insertContactSql);
+//            }
+//
+//            // 保存标签
+//            foreach ($mytag as $tag) {
+//                if (!empty(trim($tag))) {
+//                    $tagSql = "INSERT INTO tagtable (tagName, employeeId, customerId) VALUES ('" .
+//                             mysqli_real_escape_string($conn, $tag) . "', " .
+//                             $_SESSION['employee_id'] . ", $new_customer_id)";
+//                    mysqli_query($conn, $tagSql);
+//                }
+//            }
+//
+//            $page = $_GET['Page'] ?? '';
+//            $keys = urlencode($_GET['Keys'] ?? '');
+//            header("Location: ?keys=$keys&Page=$page$urlStr");
+//            exit;
+//        }
+//    }
+//}
+//
+//// 处理编辑操作
+//if ($act == "edit") {
+//    $id = $_GET['id'] ?? '';
+//    $isedit = false;
+//    if (!empty($id) && is_numeric($id)) {
+//        $isedit = true;
+//    }
+//
+//    if ($isedit) {
+//        // 联合查询客户基本信息和联系人信息
+//        $sql = "SELECT c.*,
+//                cc.id as contact_id, cc.contact_name,
+//                cc.tel_1, cc.tel_1_format, cc.tel_1_bu,
+//                cc.tel_2, cc.tel_2_format, cc.tel_2_bu,
+//                cc.tel_3, cc.tel_3_format, cc.tel_3_bu,
+//                cc.email_1, cc.email_1_bu,
+//                cc.email_2, cc.email_2_bu,
+//                cc.email_3, cc.email_3_bu,
+//                cc.whatsapp_1, cc.whatsapp_1_format, cc.whatsapp_1_bu,
+//                cc.whatsapp_2, cc.whatsapp_2_format, cc.whatsapp_2_bu,
+//                cc.whatsapp_3, cc.whatsapp_3_format, cc.whatsapp_3_bu,
+//                cc.wechat_1, cc.wechat_1_bu,
+//                cc.wechat_2, cc.wechat_2_bu,
+//                cc.wechat_3, cc.wechat_3_bu,
+//                cc.linkedin_1, cc.linkedin_1_bu,
+//                cc.linkedin_2, cc.linkedin_2_bu,
+//                cc.linkedin_3, cc.linkedin_3_bu,
+//                cc.facebook_1, cc.facebook_1_bu,
+//                cc.facebook_2, cc.facebook_2_bu,
+//                cc.facebook_3, cc.facebook_3_bu,
+//                cc.alibaba_1, cc.alibaba_1_bu,
+//                cc.alibaba_2, cc.alibaba_2_bu,
+//                cc.alibaba_3, cc.alibaba_3_bu
+//                FROM customer c
+//                LEFT JOIN customer_contact cc ON c.id = cc.customer_id
+//                WHERE c.id = $id";
+//        $result = mysqli_query($conn, $sql);
+//        if ($row = mysqli_fetch_assoc($result)) {
+//            $cs_code = textDecode($row['cs_code']);
+//            $cs_company = textDecode($row['cs_company']);
+//            $cs_name = textDecode($row['contact_name']);
+//            $cs_country = $row['cs_country'];
+//            $cs_from = $row['cs_from'];
+//            $cs_tel = textDecode($row['tel_1']);
+//            $cs_telBu = textDecode($row['tel_1_bu']);
+//            $cs_email = textDecode($row['email_1']);
+//            $cs_emailBu = textDecode($row['email_1_bu']);
+//            $cs_whatsapp = textDecode($row['whatsapp_1']);
+//            $cs_whatsappBu = textDecode($row['whatsapp_1_bu']);
+//            $cs_wechat = textDecode($row['wechat_1']);
+//            $cs_wechatBu = textDecode($row['wechat_1_bu']);
+//            $cs_linkedin = textDecode($row['linkedin_1']);
+//            $cs_linkedinBu = textDecode($row['linkedin_1_bu']);
+//            $cs_facebook = textDecode($row['facebook_1']);
+//            $cs_facebookBu = textDecode($row['facebook_1_bu']);
+//            $cs_alibaba = textDecode($row['alibaba_1']);
+//            $cs_alibabaBu = textDecode($row['alibaba_1_bu']);
+//            $cs_address = textDecode($row['cs_address']);
+//            $cs_addtime = $row['cs_addtime'];
+//            $cs_updatetime = $row['cs_updatetime'];
+//            $cs_belong = $row['cs_belong'];
+//            $cs_state = $row['cs_state'];
+//            $cs_deal = $row['cs_deal'];
+//            $cs_note = htmlDecode($row['cs_note']);
+//            $allowedit = $row['allowedit'];
+//        }
+//    }
+//}
 
 // 处理批量操作
 if ($act == "postchk") {
@@ -643,13 +644,13 @@ if (!empty($filters['Business'])) {
 
 if (!empty($filters['Contact'])) {
     switch ($filters['Contact']) {
-        case "1": $filterStr .= " AND (cc.tel_1 != '' OR cc.tel_2 != '' OR cc.tel_3 != '')"; break;
-        case "2": $filterStr .= " AND (cc.wechat_1 != '' OR cc.wechat_2 != '' OR cc.wechat_3 != '')"; break;
-        case "3": $filterStr .= " AND (cc.whatsapp_1 != '' OR cc.whatsapp_2 != '' OR cc.whatsapp_3 != '')"; break;
-        case "4": $filterStr .= " AND (cc.email_1 != '' OR cc.email_2 != '' OR cc.email_3 != '')"; break;
-        case "5": $filterStr .= " AND (cc.linkedin_1 != '' OR cc.linkedin_2 != '' OR cc.linkedin_3 != '')"; break;
-        case "6": $filterStr .= " AND (cc.facebook_1 != '' OR cc.facebook_2 != '' OR cc.facebook_3 != '')"; break;
-        case "7": $filterStr .= " AND (cc.alibaba_1 != '' OR cc.alibaba_2 != '' OR cc.alibaba_3 != '')"; break;
+        case "1": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE tel_1 != '' OR tel_2 != '' OR tel_3 != '')"; break;
+        case "2": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE wechat_1 != '' OR wechat_2 != '' OR wechat_3 != '')"; break;
+        case "3": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE whatsapp_1 != '' OR whatsapp_2 != '' OR whatsapp_3 != '')"; break;
+        case "4": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE email_1 != '' OR email_2 != '' OR email_3 != '')"; break;
+        case "5": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE linkedin_1 != '' OR linkedin_2 != '' OR linkedin_3 != '')"; break;
+        case "6": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE facebook_1 != '' OR facebook_2 != '' OR facebook_3 != '')"; break;
+        case "7": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE alibaba_1 != '' OR alibaba_2 != '' OR alibaba_3 != '')"; break;
     }
     $urlStr .= "&fliterContact=" . $filters['Contact'];
 }

+ 7 - 7
customersFollow.php

@@ -91,13 +91,13 @@ if (!empty($filterBusiness)) {
 
 if (!empty($filterContact)) {
     switch ($filterContact) {
-        case "1": $filterStr .= " AND (cc.tel_1 IS NOT NULL AND cc.tel_1 <> '' OR cc.tel_2 IS NOT NULL AND cc.tel_2 <> '' OR cc.tel_3 IS NOT NULL AND cc.tel_3 <> '')"; break;
-        case "2": $filterStr .= " AND (cc.wechat_1 IS NOT NULL AND cc.wechat_1 <> '' OR cc.wechat_2 IS NOT NULL AND cc.wechat_2 <> '' OR cc.wechat_3 IS NOT NULL AND cc.wechat_3 <> '')"; break;
-        case "3": $filterStr .= " AND (cc.whatsapp_1 IS NOT NULL AND cc.whatsapp_1 <> '' OR cc.whatsapp_2 IS NOT NULL AND cc.whatsapp_2 <> '' OR cc.whatsapp_3 IS NOT NULL AND cc.whatsapp_3 <> '')"; break;
-        case "4": $filterStr .= " AND (cc.email_1 IS NOT NULL AND cc.email_1 <> '' OR cc.email_2 IS NOT NULL AND cc.email_2 <> '' OR cc.email_3 IS NOT NULL AND cc.email_3 <> '')"; break;
-        case "5": $filterStr .= " AND (cc.linkedin_1 IS NOT NULL AND cc.linkedin_1 <> '' OR cc.linkedin_2 IS NOT NULL AND cc.linkedin_2 <> '' OR cc.linkedin_3 IS NOT NULL AND cc.linkedin_3 <> '')"; break;
-        case "6": $filterStr .= " AND (cc.facebook_1 IS NOT NULL AND cc.facebook_1 <> '' OR cc.facebook_2 IS NOT NULL AND cc.facebook_2 <> '' OR cc.facebook_3 IS NOT NULL AND cc.facebook_3 <> '')"; break;
-        default: $filterStr .= " AND (cc.alibaba_1 IS NOT NULL AND cc.alibaba_1 <> '' OR cc.alibaba_2 IS NOT NULL AND cc.alibaba_2 <> '' OR cc.alibaba_3 IS NOT NULL AND cc.alibaba_3 <> '')";
+        case "1": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE tel_1 != '' OR tel_2 != '' OR tel_3 != '')"; break;
+        case "2": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE wechat_1 != '' OR wechat_2 != '' OR wechat_3 != '')"; break;
+        case "3": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE whatsapp_1 != '' OR whatsapp_2 != '' OR whatsapp_3 != '')"; break;
+        case "4": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE email_1 != '' OR email_2 != '' OR email_3 != '')"; break;
+        case "5": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE linkedin_1 != '' OR linkedin_2 != '' OR linkedin_3 != '')"; break;
+        case "6": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE facebook_1 != '' OR facebook_2 != '' OR facebook_3 != '')"; break;
+        case "7": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE alibaba_1 != '' OR alibaba_2 != '' OR alibaba_3 != '')"; break;
     }
     $urlStr .= "&fliterContact=" . $filterContact;
 }

+ 141 - 135
customersNew.php

@@ -58,7 +58,7 @@ if ($act == "postchk") {
 
 $keys = $_GET['Keys'] ?? '';
 $keyscode = textEncode($keys);
-$page = $_GET['Page'] ?? '';
+$page = $_GET['Page'] ?? 1;
 
 $filterCountry = $_GET['fliterCountry'] ?? '';
 $filterQudao = $_GET['fliterQudao'] ?? '';
@@ -91,13 +91,13 @@ if (!empty($filterBusiness)) {
 
 if (!empty($filterContact)) {
     switch ($filterContact) {
-        case "1": $filterStr .= " AND (cc.tel_1 IS NOT NULL AND cc.tel_1 <> '' OR cc.tel_2 IS NOT NULL AND cc.tel_2 <> '' OR cc.tel_3 IS NOT NULL AND cc.tel_3 <> '')"; break;
-        case "2": $filterStr .= " AND (cc.wechat_1 IS NOT NULL AND cc.wechat_1 <> '' OR cc.wechat_2 IS NOT NULL AND cc.wechat_2 <> '' OR cc.wechat_3 IS NOT NULL AND cc.wechat_3 <> '')"; break;
-        case "3": $filterStr .= " AND (cc.whatsapp_1 IS NOT NULL AND cc.whatsapp_1 <> '' OR cc.whatsapp_2 IS NOT NULL AND cc.whatsapp_2 <> '' OR cc.whatsapp_3 IS NOT NULL AND cc.whatsapp_3 <> '')"; break;
-        case "4": $filterStr .= " AND (cc.email_1 IS NOT NULL AND cc.email_1 <> '' OR cc.email_2 IS NOT NULL AND cc.email_2 <> '' OR cc.email_3 IS NOT NULL AND cc.email_3 <> '')"; break;
-        case "5": $filterStr .= " AND (cc.linkedin_1 IS NOT NULL AND cc.linkedin_1 <> '' OR cc.linkedin_2 IS NOT NULL AND cc.linkedin_2 <> '' OR cc.linkedin_3 IS NOT NULL AND cc.linkedin_3 <> '')"; break;
-        case "6": $filterStr .= " AND (cc.facebook_1 IS NOT NULL AND cc.facebook_1 <> '' OR cc.facebook_2 IS NOT NULL AND cc.facebook_2 <> '' OR cc.facebook_3 IS NOT NULL AND cc.facebook_3 <> '')"; break;
-        default: $filterStr .= " AND (cc.alibaba_1 IS NOT NULL AND cc.alibaba_1 <> '' OR cc.alibaba_2 IS NOT NULL AND cc.alibaba_2 <> '' OR cc.alibaba_3 IS NOT NULL AND cc.alibaba_3 <> '')";
+        case "1": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE tel_1 != '' OR tel_2 != '' OR tel_3 != '')"; break;
+        case "2": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE wechat_1 != '' OR wechat_2 != '' OR wechat_3 != '')"; break;
+        case "3": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE whatsapp_1 != '' OR whatsapp_2 != '' OR whatsapp_3 != '')"; break;
+        case "4": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE email_1 != '' OR email_2 != '' OR email_3 != '')"; break;
+        case "5": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE linkedin_1 != '' OR linkedin_2 != '' OR linkedin_3 != '')"; break;
+        case "6": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE facebook_1 != '' OR facebook_2 != '' OR facebook_3 != '')"; break;
+        case "7": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE alibaba_1 != '' OR alibaba_2 != '' OR alibaba_3 != '')"; break;
     }
     $urlStr .= "&fliterContact=" . $filterContact;
 }
@@ -172,9 +172,8 @@ $hrefstr = "?keys=" . $keys;
         </div>
         <div class="inputSearch">
             <input type="text" id="keys" class="inputTxt" 
-                value="<?= empty($keyscode) ? '请输入搜索关键词' : $keyscode ?>" 
-                onFocus="if(this.value == '<?= empty($keyscode) ? '请输入搜索关键词' : $keyscode ?>'){this.value='';}" 
-                onBlur="if(this.value == ''){this.value='<?= empty($keyscode) ? '请输入搜索关键词' : $keyscode ?>';}" 
+                placeholder="请输入搜索关键词"
+                value="<?= empty($keyscode) ? '' : $keyscode ?>" 
                 onKeyDown="if(event.keyCode==13){location.href='?Keys='+encodeURIComponent(document.getElementById('keys').value)}" />
             <input type="button" id="searchgo" class="searchgo" value="go" 
                 onClick="location.href='?Keys='+encodeURIComponent(document.getElementById('keys').value)" />
@@ -197,75 +196,60 @@ $hrefstr = "?keys=" . $keys;
 
 <?php
 $employee_id = intval($_SESSION['employee_id']);
-$escapedKeyscode = $conn->real_escape_string($keyscode);
+$searchPattern = mysqli_real_escape_string($conn, $keyscode);
 
-$sql = "SELECT c.id, 
-        MAX(c.cs_code) as cs_code, 
-        MAX(c.cs_from) as cs_from, 
-        MAX(c.cs_country) as cs_country, 
-        MAX(c.cs_type) as cs_type, 
-        MAX(c.cs_deal) as cs_deal, 
-        MAX(c.cs_addtime) as cs_addtime, 
-        MAX(c.colorTag) as colorTag, 
-        MAX(c.cs_note) as cs_note,
-        GROUP_CONCAT(DISTINCT cc.id) as contact_ids,
-        GROUP_CONCAT(DISTINCT cc.contact_name) as contact_names,
-        GROUP_CONCAT(DISTINCT cc.tel_1) as tel_1_list,
-        GROUP_CONCAT(DISTINCT cc.tel_2) as tel_2_list,
-        GROUP_CONCAT(DISTINCT cc.tel_3) as tel_3_list,
-        GROUP_CONCAT(DISTINCT cc.email_1) as email_1_list,
-        GROUP_CONCAT(DISTINCT cc.email_2) as email_2_list,
-        GROUP_CONCAT(DISTINCT cc.email_3) as email_3_list,
-        GROUP_CONCAT(DISTINCT cc.whatsapp_1) as whatsapp_1_list,
-        GROUP_CONCAT(DISTINCT cc.whatsapp_2) as whatsapp_2_list,
-        GROUP_CONCAT(DISTINCT cc.whatsapp_3) as whatsapp_3_list,
-        GROUP_CONCAT(DISTINCT cc.wechat_1) as wechat_1_list,
-        GROUP_CONCAT(DISTINCT cc.wechat_2) as wechat_2_list,
-        GROUP_CONCAT(DISTINCT cc.wechat_3) as wechat_3_list,
-        GROUP_CONCAT(DISTINCT cc.linkedin_1) as linkedin_1_list,
-        GROUP_CONCAT(DISTINCT cc.linkedin_2) as linkedin_2_list,
-        GROUP_CONCAT(DISTINCT cc.linkedin_3) as linkedin_3_list,
-        GROUP_CONCAT(DISTINCT cc.facebook_1) as facebook_1_list,
-        GROUP_CONCAT(DISTINCT cc.facebook_2) as facebook_2_list,
-        GROUP_CONCAT(DISTINCT cc.facebook_3) as facebook_3_list,
-        GROUP_CONCAT(DISTINCT cc.alibaba_1) as alibaba_1_list,
-        GROUP_CONCAT(DISTINCT cc.alibaba_2) as alibaba_2_list,
-        GROUP_CONCAT(DISTINCT cc.alibaba_3) as alibaba_3_list
+$sql = "SELECT c.id, c.cs_code, c.cs_company, c.cs_country, c.cs_address, c.cs_from, 
+        c.cs_deal, c.cs_addtime, c.cs_updatetime, c.cs_belong, c.cs_note, c.cs_claimFrom, 
+        c.cs_chain, c.cs_dealdate, c.cs_type, c.cs_belongclient, c.allowedit, c.colorTag
         FROM customer c 
-        LEFT JOIN customer_contact cc ON c.id = cc.customer_id 
         WHERE c.cs_belong=" . $employee_id . " 
         AND MONTH(c.cs_addtime) = MONTH(CURRENT_DATE()) 
-        AND YEAR(c.cs_addtime) = YEAR(CURRENT_DATE())
-        AND (c.cs_code LIKE '%" . $escapedKeyscode . "%' 
-        OR cc.contact_name LIKE '%" . $escapedKeyscode . "%'
-        OR cc.email_1 LIKE '%" . $escapedKeyscode . "%' OR cc.email_2 LIKE '%" . $escapedKeyscode . "%' OR cc.email_3 LIKE '%" . $escapedKeyscode . "%'
-        OR cc.wechat_1 LIKE '%" . $escapedKeyscode . "%' OR cc.wechat_2 LIKE '%" . $escapedKeyscode . "%' OR cc.wechat_3 LIKE '%" . $escapedKeyscode . "%'
-        OR cc.tel_1 LIKE '%" . $escapedKeyscode . "%' OR cc.tel_2 LIKE '%" . $escapedKeyscode . "%' OR cc.tel_3 LIKE '%" . $escapedKeyscode . "%'
-        OR cc.whatsapp_1 LIKE '%" . $escapedKeyscode . "%' OR cc.whatsapp_2 LIKE '%" . $escapedKeyscode . "%' OR cc.whatsapp_3 LIKE '%" . $escapedKeyscode . "%')" . 
-        $filterStr . " GROUP BY c.id ORDER BY c.id DESC";
+        AND YEAR(c.cs_addtime) = YEAR(CURRENT_DATE())";
 
-$result = $conn->query($sql);
+if(!empty($searchPattern)) {
+    $sql .= " AND (c.cs_code LIKE '%$searchPattern%' 
+            OR c.id IN (SELECT customer_id FROM customer_contact WHERE 
+                contact_name LIKE '%$searchPattern%' OR
+                tel_1 LIKE '%$searchPattern%' OR
+                tel_2 LIKE '%$searchPattern%' OR
+                tel_3 LIKE '%$searchPattern%' OR
+                email_1 LIKE '%$searchPattern%' OR
+                email_2 LIKE '%$searchPattern%' OR
+                email_3 LIKE '%$searchPattern%' OR
+                wechat_1 LIKE '%$searchPattern%' OR
+                wechat_2 LIKE '%$searchPattern%' OR
+                wechat_3 LIKE '%$searchPattern%' OR
+                whatsapp_1_format LIKE '%$searchPattern%' OR
+                whatsapp_2_format LIKE '%$searchPattern%' OR
+                whatsapp_3_format LIKE '%$searchPattern%' OR
+                linkedin_1 LIKE '%$searchPattern%' OR
+                linkedin_2 LIKE '%$searchPattern%' OR
+                linkedin_3 LIKE '%$searchPattern%' OR
+                facebook_1 LIKE '%$searchPattern%' OR
+                facebook_2 LIKE '%$searchPattern%' OR
+                facebook_3 LIKE '%$searchPattern%' OR
+                alibaba_1 LIKE '%$searchPattern%' OR
+                alibaba_2 LIKE '%$searchPattern%' OR
+                alibaba_3 LIKE '%$searchPattern%')
+            OR c.id IN (SELECT customerId FROM tagtable WHERE tagName LIKE '%$searchPattern%'))";
+}
 
-if ($result && $result->num_rows > 0) {
-    $pageSize = 20;
-    $page = empty($page) ? 1 : $page;
-    $page = ($page === 'end') ? ceil($result->num_rows / $pageSize) : $page;
-    $page = (!is_numeric($page) || $page < 1) ? 1 : (int)$page;
-    $totalPages = ceil($result->num_rows / $pageSize);
-    $page = ($page > $totalPages) ? $totalPages : $page;
-    $offset = $pageSize * ($page - 1);
-    
-    // Store results in array for pagination
-    $rows = [];
-    while ($row = $result->fetch_assoc()) {
-        $rows[] = $row;
-    }
-    
-    // Get paginated results
-    $paginatedRows = array_slice($rows, $offset, $pageSize);
+$sql .= " $filterStr ORDER BY c.colorTag DESC, c.id DESC";
+
+// Pagination logic
+$result = mysqli_query($conn, $sql);
+$totalRecords = mysqli_num_rows($result);
+$totalPages = max(1, ceil($totalRecords / 20));
+$page = max(1, min((int)$page, $totalPages));
+$offset = max(0, ($page - 1) * 20);
+
+// Add pagination to query
+$sql .= " LIMIT $offset, 20";
+$result = mysqli_query($conn, $sql);
+
+if (mysqli_num_rows($result) > 0) {
     $tempNum = $offset;
-    
-    foreach ($paginatedRows as $row) {
+    while ($row = mysqli_fetch_assoc($result)) {
         $tempNum++;
 ?>
         <div class="tline color<?= $row['colorTag'] ?>">
@@ -328,63 +312,91 @@ if ($result && $result->num_rows > 0) {
                 // Fetch all contacts for this customer
                 $contact_sql = "SELECT * FROM customer_contact WHERE customer_id = " . $row['id'];
                 $contact_result = mysqli_query($conn, $contact_sql);
-                
-                if ($contact_result && mysqli_num_rows($contact_result) > 0) {
-                    while ($contact = mysqli_fetch_assoc($contact_result)) {
-                        echo '<div class="contact-block" style="margin-bottom: 10px; border-bottom: 1px dashed #ccc; padding-bottom: 5px;">';
-                        
-                        if (!empty($contact['contact_name'])) {
-                            echo '<div class="contact-name"><strong>' . htmlspecialcharsFix($contact['contact_name']) . '</strong></div>';
-                        }
-                        
-                        echo '<div class="tel">';
-                        if (!empty($contact['tel_1'])) echo '电话: ' . htmlspecialcharsFix($contact['tel_1']) . '<br>';
-                        if (!empty($contact['tel_2'])) echo '电话: ' . htmlspecialcharsFix($contact['tel_2']) . '<br>';
-                        if (!empty($contact['tel_3'])) echo '电话: ' . htmlspecialcharsFix($contact['tel_3']) . '<br>';
-                        echo '</div>';
-                        
-                        echo '<div class="mail">';
-                        if (!empty($contact['email_1'])) echo '邮箱: <a href="mailto:' . htmlspecialcharsFix($contact['email_1']) . '">' . htmlspecialcharsFix($contact['email_1']) . '</a><br>';
-                        if (!empty($contact['email_2'])) echo '邮箱: <a href="mailto:' . htmlspecialcharsFix($contact['email_2']) . '">' . htmlspecialcharsFix($contact['email_2']) . '</a><br>';
-                        if (!empty($contact['email_3'])) echo '邮箱: <a href="mailto:' . htmlspecialcharsFix($contact['email_3']) . '">' . htmlspecialcharsFix($contact['email_3']) . '</a><br>';
-                        echo '</div>';
-                        
-                        echo '<div class="whatsapp">';
-                        if (!empty($contact['whatsapp_1'])) echo 'WhatsApp: ' . htmlspecialcharsFix($contact['whatsapp_1']) . '<br>';
-                        if (!empty($contact['whatsapp_2'])) echo 'WhatsApp: ' . htmlspecialcharsFix($contact['whatsapp_2']) . '<br>';
-                        if (!empty($contact['whatsapp_3'])) echo 'WhatsApp: ' . htmlspecialcharsFix($contact['whatsapp_3']) . '<br>';
-                        echo '</div>';
-                        
-                        echo '<div class="wechat">';
-                        if (!empty($contact['wechat_1'])) echo '微信: ' . htmlspecialcharsFix($contact['wechat_1']) . '<br>';
-                        if (!empty($contact['wechat_2'])) echo '微信: ' . htmlspecialcharsFix($contact['wechat_2']) . '<br>';
-                        if (!empty($contact['wechat_3'])) echo '微信: ' . htmlspecialcharsFix($contact['wechat_3']) . '<br>';
-                        echo '</div>';
-                        
-                        echo '<div class="linkedin">';
-                        if (!empty($contact['linkedin_1'])) echo '领英: ' . htmlspecialcharsFix($contact['linkedin_1']) . '<br>';
-                        if (!empty($contact['linkedin_2'])) echo '领英: ' . htmlspecialcharsFix($contact['linkedin_2']) . '<br>';
-                        if (!empty($contact['linkedin_3'])) echo '领英: ' . htmlspecialcharsFix($contact['linkedin_3']) . '<br>';
-                        echo '</div>';
-                        
-                        echo '<div class="facebook">';
-                        if (!empty($contact['facebook_1'])) echo 'Facebook: ' . htmlspecialcharsFix($contact['facebook_1']) . '<br>';
-                        if (!empty($contact['facebook_2'])) echo 'Facebook: ' . htmlspecialcharsFix($contact['facebook_2']) . '<br>';
-                        if (!empty($contact['facebook_3'])) echo 'Facebook: ' . htmlspecialcharsFix($contact['facebook_3']) . '<br>';
-                        echo '</div>';
-                        
-                        echo '<div class="alibaba">';
-                        if (!empty($contact['alibaba_1'])) echo '阿里: ' . htmlspecialcharsFix($contact['alibaba_1']) . '<br>';
-                        if (!empty($contact['alibaba_2'])) echo '阿里: ' . htmlspecialcharsFix($contact['alibaba_2']) . '<br>';
-                        if (!empty($contact['alibaba_3'])) echo '阿里: ' . htmlspecialcharsFix($contact['alibaba_3']) . '<br>';
-                        echo '</div>';
-                        
-                        echo '</div>';
-                    }
-                } else {
-                    echo '<div>无联系人信息</div>';
-                }
+                while ($contact = mysqli_fetch_assoc($contact_result)) {
                 ?>
+                <div class="contact-block">
+                    <?php if(!empty($contact['contact_name'])): ?>
+                        <div class="contact-name"><?= htmlspecialcharsFix($contact['contact_name']) ?></div>
+                    <?php endif; ?>
+                    <div class="tel">
+                        <?php if(!empty($contact['tel_1'])): ?>
+                            <div><?= htmlspecialcharsFix($contact['tel_1']) ?></div>
+                        <?php endif; ?>
+                        <?php if(!empty($contact['tel_2'])): ?>
+                            <div><?= htmlspecialcharsFix($contact['tel_2']) ?></div>
+                        <?php endif; ?>
+                        <?php if(!empty($contact['tel_3'])): ?>
+                            <div><?= htmlspecialcharsFix($contact['tel_3']) ?></div>
+                        <?php endif; ?>
+                    </div>
+                    <div class="mail">
+                        <?php if(!empty($contact['email_1'])): ?>
+                            <div><a href="mailto:<?= htmlspecialcharsFix($contact['email_1']) ?>"><?= htmlspecialcharsFix($contact['email_1']) ?></a></div>
+                        <?php endif; ?>
+                        <?php if(!empty($contact['email_2'])): ?>
+                            <div><a href="mailto:<?= htmlspecialcharsFix($contact['email_2']) ?>"><?= htmlspecialcharsFix($contact['email_2']) ?></a></div>
+                        <?php endif; ?>
+                        <?php if(!empty($contact['email_3'])): ?>
+                            <div><a href="mailto:<?= htmlspecialcharsFix($contact['email_3']) ?>"><?= htmlspecialcharsFix($contact['email_3']) ?></a></div>
+                        <?php endif; ?>
+                    </div>
+                    <div class="whatsapp">
+                        <?php if(!empty($contact['whatsapp_1'])): ?>
+                            <div><?= htmlspecialcharsFix($contact['whatsapp_1']) ?></div>
+                        <?php endif; ?>
+                        <?php if(!empty($contact['whatsapp_2'])): ?>
+                            <div><?= htmlspecialcharsFix($contact['whatsapp_2']) ?></div>
+                        <?php endif; ?>
+                        <?php if(!empty($contact['whatsapp_3'])): ?>
+                            <div><?= htmlspecialcharsFix($contact['whatsapp_3']) ?></div>
+                        <?php endif; ?>
+                    </div>
+                    <div class="wechat">
+                        <?php if(!empty($contact['wechat_1'])): ?>
+                            <div><?= htmlspecialcharsFix($contact['wechat_1']) ?></div>
+                        <?php endif; ?>
+                        <?php if(!empty($contact['wechat_2'])): ?>
+                            <div><?= htmlspecialcharsFix($contact['wechat_2']) ?></div>
+                        <?php endif; ?>
+                        <?php if(!empty($contact['wechat_3'])): ?>
+                            <div><?= htmlspecialcharsFix($contact['wechat_3']) ?></div>
+                        <?php endif; ?>
+                    </div>
+                    <div class="linkedin">
+                        <?php if(!empty($contact['linkedin_1'])): ?>
+                            <div><?= htmlspecialcharsFix($contact['linkedin_1']) ?></div>
+                        <?php endif; ?>
+                        <?php if(!empty($contact['linkedin_2'])): ?>
+                            <div><?= htmlspecialcharsFix($contact['linkedin_2']) ?></div>
+                        <?php endif; ?>
+                        <?php if(!empty($contact['linkedin_3'])): ?>
+                            <div><?= htmlspecialcharsFix($contact['linkedin_3']) ?></div>
+                        <?php endif; ?>
+                    </div>
+                    <div class="facebook">
+                        <?php if(!empty($contact['facebook_1'])): ?>
+                            <div><?= htmlspecialcharsFix($contact['facebook_1']) ?></div>
+                        <?php endif; ?>
+                        <?php if(!empty($contact['facebook_2'])): ?>
+                            <div><?= htmlspecialcharsFix($contact['facebook_2']) ?></div>
+                        <?php endif; ?>
+                        <?php if(!empty($contact['facebook_3'])): ?>
+                            <div><?= htmlspecialcharsFix($contact['facebook_3']) ?></div>
+                        <?php endif; ?>
+                    </div>
+                    <div class="alibaba">
+                        <?php if(!empty($contact['alibaba_1'])): ?>
+                            <div><?= htmlspecialcharsFix($contact['alibaba_1']) ?></div>
+                        <?php endif; ?>
+                        <?php if(!empty($contact['alibaba_2'])): ?>
+                            <div><?= htmlspecialcharsFix($contact['alibaba_2']) ?></div>
+                        <?php endif; ?>
+                        <?php if(!empty($contact['alibaba_3'])): ?>
+                            <div><?= htmlspecialcharsFix($contact['alibaba_3']) ?></div>
+                        <?php endif; ?>
+                    </div>
+                </div>
+                <?php } ?>
             </div>
             <div class="noteItem2">备注</div>
             <div class="notecontent"><?= htmlUnCode($row['cs_note']) ?></div>
@@ -453,12 +465,6 @@ if (isset($totalPages) && $totalPages > 1) {
         echo "<a href=\"{$pageName}Page=" . ($page + 1) . "\">下一页</a>";
         echo "<a href=\"{$pageName}Page={$totalPages}\">尾页</a>";
     }
-    
-    echo "<input type=\"text\" id=\"Pagego\" value=\"{$page}\" 
-          onFocus=\"if(this.value == '{$page}'){this.value='';}\" 
-          onBlur=\"if(this.value == ''){this.value='{$page}';}\" 
-          onKeyUp=\"this.value=this.value.replace(/\D/g,'')\" 
-          onKeyDown=\"if(event.keyCode==13){location.href='{$pageName}Page='+document.getElementById('Pagego').value}\" />";
 }
 ?>
             </div>

+ 149 - 7
customers_stats.php

@@ -15,6 +15,18 @@ 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'];
+}
+
 // 获取日期范围参数
 $date_params = getDateRangeParams();
 $start_date = $date_params['start_date_sql'];
@@ -54,6 +66,38 @@ include('statistics_header.php');
                 <label for="end_date">结束日期</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">
+                <label for="selected_employee">选择业务员</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">应用筛选</button>
             </div>
@@ -66,12 +110,45 @@ include('statistics_header.php');
             <h2>关键指标</h2>
         </div>
         <?php
+        // 获取选择的业务员
+        $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);
+            }
+        }
+        
         // 获取关键指标数据
-        $total_customers = getTotalCustomers($conn);
-        $new_customers = getNewCustomers($conn, $start_date, $end_date);
-        $avg_customer_value = getAverageCustomerValue($conn, $start_date, $end_date);
-        $retention_data = getCustomerRetentionRate($conn, $start_date, $end_date);
-        $conversion_data = getOrderConversionRate($conn, $start_date, $end_date);
+        $total_customers = getTotalCustomers($conn, $employee_filter);
+        $new_customers = getNewCustomers($conn, $start_date, $end_date, $employee_filter);
+        $avg_customer_value = getAverageCustomerValue($conn, $start_date, $end_date, $employee_filter);
+        $retention_data = getCustomerRetentionRate($conn, $start_date, $end_date, $employee_filter);
+        $conversion_data = getOrderConversionRate($conn, $start_date, $end_date, $employee_filter);
 
         // 组合所有指标数据
         $kpi_data = [
@@ -96,8 +173,40 @@ include('statistics_header.php');
             <h2>新增客户明细</h2>
         </div>
         <?php
+        // 获取选择的业务员
+        $selected_employee = isset($_GET['selected_employee']) ? $_GET['selected_employee'] : 'all';
+        
         // 获取新增客户详细数据
-        $new_customers_details = getNewCustomersDetails($conn, $start_date, $end_date);
+        $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);
+            }
+        }
+        
+        $new_customers_details = getNewCustomersDetails($conn, $start_date, $end_date, $employee_filter);
         
         // 渲染新增客户图表
         renderNewCustomersChart($new_customers_details);
@@ -110,8 +219,41 @@ include('statistics_header.php');
             <h2>业务员新增客户统计</h2>
         </div>
         <?php
+        // 获取选择的业务员
+        $selected_employee = isset($_GET['selected_employee']) ? $_GET['selected_employee'] : 'all';
+        
         // 获取各业务员新增客户数据
-        $employee_new_customers = getNewCustomersByEmployee($conn, $start_date, $end_date);
+        // 根据权限角色和选择的业务员过滤业务员数据
+        $visible_employees = [];
+        
+        if ($selected_employee != 'all') {
+            // 如果选择了特定业务员,则只显示该业务员的数据
+            $visible_employees = [intval($selected_employee)];
+            $employee_new_customers = getNewCustomersByEmployee($conn, $start_date, $end_date, $visible_employees);
+        } else {
+            // 否则按权限显示相应的业务员数据
+            if ($current_permission_role == 1) {
+                // 管理员可以看到所有业务员
+                $employee_new_customers = getNewCustomersByEmployee($conn, $start_date, $end_date);
+            } 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_new_customers = getNewCustomersByEmployee($conn, $start_date, $end_date, $visible_employees);
+            } else {
+                // 组员只能看到自己
+                $visible_employees = [intval($current_employee_id)];
+                $employee_new_customers = getNewCustomersByEmployee($conn, $start_date, $end_date, $visible_employees);
+            }
+        }
         
         // 渲染业务员新增客户图表
         renderNewCustomersByEmployeeChart($employee_new_customers);

+ 85 - 16
products_stats.php

@@ -11,6 +11,18 @@ if (!isset($_SESSION['employee_id'])) {
     checkLogin();
 }
 
+// 获取当前登录用户信息
+$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'];
+}
+
 // 获取日期范围参数
 $date_params = getDateRangeParams();
 $start_date = $date_params['start_date_sql'];
@@ -52,14 +64,38 @@ include('statistics_header.php');
                 <label for="end_date">结束日期</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">
-                <label for="period">时间粒度</label>
-                <select class="form-control" id="period" name="period">
-                    <option value="day" <?php echo $period == 'day' ? 'selected' : ''; ?>>日</option>
-                    <option value="week" <?php echo $period == 'week' ? 'selected' : ''; ?>>周</option>
-                    <option value="month" <?php echo $period == 'month' ? 'selected' : ''; ?>>月</option>
+                <label for="selected_employee">选择业务员</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">
                 <label for="category_id">产品分类</label>
                 <select class="form-control" id="category_id" name="category_id">
@@ -86,7 +122,40 @@ include('statistics_header.php');
             <h2>产品销售概览</h2>
         </div>
         <?php
-        $sales_overview = getProductSalesOverview($conn, $start_date, $end_date, $category_filter);
+        // 获取选择的业务员
+        $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[] = intval($row['id']);
+                    }
+                }
+                
+                $employee_filter = $visible_employees;
+            } else {
+                // 组员只能看到自己
+                $employee_filter = intval($current_employee_id);
+            }
+        }
+        
+        $sales_overview = getProductSalesOverview($conn, $start_date, $end_date, $category_filter, $employee_filter);
         renderProductSalesOverview($sales_overview);
         ?>
     </div>
@@ -94,7 +163,7 @@ include('statistics_header.php');
     <!-- 热门产品 -->
     <div class="chart-container">
         <?php
-        $top_products = getTopProducts($conn, $start_date, $end_date, 10);
+        $top_products = getTopProducts($conn, $start_date, $end_date, 10, $employee_filter);
         renderTopProductsTable($top_products);
         ?>
     </div>
@@ -105,7 +174,7 @@ include('statistics_header.php');
             <h2>新客户购买产品明细</h2>
         </div>
         <?php
-        $new_customer_products = getNewCustomerProductPurchases($conn, $start_date, $end_date, $category_filter);
+        $new_customer_products = getNewCustomerProductPurchases($conn, $start_date, $end_date, $category_filter, $employee_filter);
         renderNewCustomerProductPurchases($new_customer_products);
         ?>
     </div>
@@ -113,7 +182,7 @@ include('statistics_header.php');
     <!-- 产品销售趋势 -->
     <div class="chart-container" style="display: none">
         <?php
-        $product_trends = getProductSalesTrend($conn, $start_date, $end_date, $product_id, $period);
+        $product_trends = getProductSalesTrend($conn, $start_date, $end_date, $product_id, $period, $employee_filter);
         
         $time_labels = [];
         $quantities = [];
@@ -131,7 +200,7 @@ include('statistics_header.php');
     <!-- 产品类别销售分布 -->
     <div class="chart-container" style="display: none">
         <?php
-        $category_sales = getProductCategorySales($conn, $start_date, $end_date);
+        $category_sales = getProductCategorySales($conn, $start_date, $end_date, $employee_filter);
         
         $categories = [];
         $category_quantities = [];
@@ -149,7 +218,7 @@ include('statistics_header.php');
     <!-- 产品价格趋势分析 -->
     <div class="chart-container" style="display: none">
         <?php
-        $price_trend_data = getProductPriceTrendAnalysis($conn, $start_date, $end_date, $product_id, $period);
+        $price_trend_data = getProductPriceTrendAnalysis($conn, $start_date, $end_date, $product_id, $period, $employee_filter);
         renderProductPriceTrendChart($price_trend_data);
         ?>
     </div>
@@ -157,7 +226,7 @@ include('statistics_header.php');
     <!-- 产品季节性分析 -->
     <div class="chart-container" style="display: none">
         <?php
-        $seasonality_data = getProductSeasonalityAnalysis($conn, $start_date, $end_date, $product_id);
+        $seasonality_data = getProductSeasonalityAnalysis($conn, $start_date, $end_date, $product_id, $employee_filter);
         renderProductSeasonalityChart($seasonality_data);
         ?>
     </div>
@@ -165,7 +234,7 @@ include('statistics_header.php');
     <!-- 产品客户细分分析 -->
     <div class="chart-container" style="display: none">
         <?php
-        $customer_segment_data = getProductCustomerSegmentAnalysis($conn, $start_date, $end_date, $product_id);
+        $customer_segment_data = getProductCustomerSegmentAnalysis($conn, $start_date, $end_date, $product_id, $employee_filter);
         renderProductCustomerSegmentChart($customer_segment_data);
         ?>
     </div>
@@ -173,7 +242,7 @@ include('statistics_header.php');
     <!-- 产品地区关联分析 -->
     <div class="chart-container" style="display: none">
         <?php
-        $product_region_data = getProductRegionAnalysis($conn, $start_date, $end_date);
+        $product_region_data = getProductRegionAnalysis($conn, $start_date, $end_date, $employee_filter);
         renderProductRegionAnalysisTable($product_region_data);
         ?>
     </div>
@@ -181,7 +250,7 @@ include('statistics_header.php');
     <!-- 产品增长率分析 -->
     <div class="chart-container" style="display: none">
         <?php
-        $growth_data = getProductGrowthAnalysis($conn, $start_date, $end_date, $period);
+        $growth_data = getProductGrowthAnalysis($conn, $start_date, $end_date, $period, $employee_filter);
         renderProductGrowthAnalysis($growth_data);
         ?>
     </div>
@@ -189,7 +258,7 @@ include('statistics_header.php');
     <!-- 产品购买频率分析 -->
     <div class="chart-container" style="display: none">
         <?php
-        $frequency_data = getProductPurchaseFrequency($conn, $start_date, $end_date);
+        $frequency_data = getProductPurchaseFrequency($conn, $start_date, $end_date, $employee_filter);
         renderProductPurchaseFrequency($frequency_data);
         ?>
     </div>

+ 85 - 16
region_stats.php

@@ -11,6 +11,18 @@ if (!isset($_SESSION['employee_id'])) {
     checkLogin();
 }
 
+// 获取当前登录用户信息
+$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'];
+}
+
 // 获取日期范围参数
 $date_params = getDateRangeParams();
 $start_date = $date_params['start_date_sql'];
@@ -52,14 +64,38 @@ include('statistics_header.php');
                 <label for="end_date">结束日期</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">
-                <label for="period">时间粒度</label>
-                <select class="form-control" id="period" name="period">
-                    <option value="day" <?php echo $period == 'day' ? 'selected' : ''; ?>>日</option>
-                    <option value="week" <?php echo $period == 'week' ? 'selected' : ''; ?>>周</option>
-                    <option value="month" <?php echo $period == 'month' ? 'selected' : ''; ?>>月</option>
+                <label for="selected_employee">选择业务员</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">
                 <label for="country_id">国家/地区</label>
                 <select class="form-control" id="country_id" name="country_id">
@@ -90,7 +126,40 @@ include('statistics_header.php');
             <div class="stat-card">
                 <h3>总销售额</h3>
                 <?php
-                $total_sales = getRegionTotalSales($conn, $start_date, $end_date);
+                // 获取选择的业务员
+                $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[] = intval($row['id']);
+                            }
+                        }
+                        
+                        $employee_filter = $visible_employees;
+                    } else {
+                        // 组员只能看到自己
+                        $employee_filter = intval($current_employee_id);
+                    }
+                }
+                
+                $total_sales = getRegionTotalSales($conn, $start_date, $end_date, $employee_filter);
                 echo "<div class='stat-value'>¥" . number_format($total_sales['total_amount'], 2) . "</div>";
                 echo "<div class='stat-trend " . ($total_sales['growth'] >= 0 ? 'positive' : 'negative') . "'>";
                 echo ($total_sales['growth'] >= 0 ? '+' : '') . number_format($total_sales['growth'], 2) . "%</div>";
@@ -100,7 +169,7 @@ include('statistics_header.php');
             <div class="stat-card">
                 <h3>活跃国家数</h3>
                 <?php
-                $active_countries = getActiveCountries($conn, $start_date, $end_date);
+                $active_countries = getActiveCountries($conn, $start_date, $end_date, $employee_filter);
                 echo "<div class='stat-value'>" . $active_countries['count'] . "</div>";
                 ?>
             </div>
@@ -108,7 +177,7 @@ include('statistics_header.php');
             <div class="stat-card">
                 <h3>平均订单金额</h3>
                 <?php
-                $avg_order = getAverageOrderByRegion($conn, $start_date, $end_date);
+                $avg_order = getAverageOrderByRegion($conn, $start_date, $end_date, $employee_filter);
                 echo "<div class='stat-value'>¥" . number_format($avg_order['global_avg'], 2) . "</div>";
                 ?>
             </div>
@@ -121,7 +190,7 @@ include('statistics_header.php');
             <h2>热门地区</h2>
         </div>
         <?php
-        $region_orders = getOrdersByRegion($conn, $start_date, $end_date);
+        $region_orders = getOrdersByRegion($conn, $start_date, $end_date, $employee_filter);
         $region_labels = [];
         $region_order_counts = [];
         $region_quantities = [];
@@ -143,7 +212,7 @@ include('statistics_header.php');
             <h2>客户国家分布</h2>
         </div>
         <?php
-        $country_distribution = getCustomerCountryDistribution($conn);
+        $country_distribution = getCustomerCountryDistribution($conn, $employee_filter);
         $country_labels = [];
         $country_data = [];
         
@@ -161,7 +230,7 @@ include('statistics_header.php');
             <h2>地区销售趋势</h2>
         </div>
         <?php
-        $growth_trends = getRegionGrowthTrends($conn, $start_date, $end_date, $period);
+        $growth_trends = getRegionGrowthTrends($conn, $start_date, $end_date, $period, $employee_filter);
         renderRegionGrowthTrendsChart($growth_trends);
         ?>
     </div>
@@ -182,7 +251,7 @@ include('statistics_header.php');
             <h2>地区平均订单金额分析</h2>
         </div>
         <?php
-        $avg_order_data = getAverageOrderByRegion($conn, $start_date, $end_date);
+        $avg_order_data = getAverageOrderByRegion($conn, $start_date, $end_date, $employee_filter);
         renderAverageOrderByRegionChart($avg_order_data['regions']);
         ?>
     </div>
@@ -193,7 +262,7 @@ include('statistics_header.php');
             <h2>各地区产品类别偏好</h2>
         </div>
         <?php
-        $category_preferences = getRegionCategoryPreferences($conn, $start_date, $end_date);
+        $category_preferences = getRegionCategoryPreferences($conn, $start_date, $end_date, $employee_filter);
         renderRegionCategoryPreferencesChart($category_preferences);
         ?>
     </div>
@@ -204,7 +273,7 @@ include('statistics_header.php');
             <h2>地区销售同比分析</h2>
         </div>
         <?php
-        $comparison_data = getRegionSalesComparison($conn, $start_date, $end_date);
+        $comparison_data = getRegionSalesComparison($conn, $start_date, $end_date, $employee_filter);
         renderRegionSalesComparisonTable($comparison_data);
         ?>
     </div>
@@ -215,7 +284,7 @@ include('statistics_header.php');
             <h2>地区季节性分析</h2>
         </div>
         <?php
-        $seasonal_analysis = getRegionSeasonalAnalysis($conn);
+        $seasonal_analysis = getRegionSeasonalAnalysis($conn, $employee_filter);
         renderRegionSeasonalAnalysisChart($seasonal_analysis);
         ?>
     </div>
@@ -226,7 +295,7 @@ include('statistics_header.php');
             <h2>地区销售预测</h2>
         </div>
         <?php
-        $forecast_data = getRegionSalesForecast($conn, $start_date, $end_date);
+        $forecast_data = getRegionSalesForecast($conn, $start_date, $end_date, $employee_filter);
         renderRegionSalesForecastChart($forecast_data);
         ?>
     </div>

+ 202 - 45
statistics_customers.php

@@ -440,10 +440,33 @@ function renderNewVsReturningCustomersChart($new_vs_returning) {
  * 获取客户总数
  * 
  * @param mysqli $conn 数据库连接
+ * @param array|int $employee_filter 业务员ID或ID数组,用于过滤数据 (可选)
  * @return int 客户总数
  */
-function getTotalCustomers($conn) {
+function getTotalCustomers($conn, $employee_filter = null) {
     $sql = "SELECT COUNT(id) as total FROM customer";
+    
+    // 如果有业务员过滤
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter) && !empty($employee_filter)) {
+            // 处理数组形式的业务员ID列表
+            $emp_ids = array();
+            foreach ($employee_filter as $emp_id) {
+                if (is_numeric($emp_id)) {
+                    $emp_ids[] = intval($emp_id);
+                }
+            }
+            if (!empty($emp_ids)) {
+                $emp_ids_str = implode(',', $emp_ids);
+                $sql .= " WHERE cs_belong IN ($emp_ids_str)";
+            }
+        } else if (is_numeric($employee_filter) && $employee_filter > 0) {
+            // 处理单个业务员ID
+            $employee_filter = intval($employee_filter);
+            $sql .= " WHERE cs_belong = $employee_filter";
+        }
+    }
+    
     $result = $conn->query($sql);
     $row = $result->fetch_assoc();
     return $row['total'];
@@ -455,17 +478,40 @@ function getTotalCustomers($conn) {
  * @param mysqli $conn 数据库连接
  * @param string $start_date 开始日期
  * @param string $end_date 结束日期
+ * @param array|int $employee_filter 业务员ID或ID数组,用于过滤数据 (可选)
  * @return int 新增客户数
  */
-function getNewCustomers($conn, $start_date, $end_date) {
+function getNewCustomers($conn, $start_date, $end_date, $employee_filter = null) {
+    // 使用 mysqli_real_escape_string 防止 SQL 注入
+    $start_date = $conn->real_escape_string($start_date);
+    $end_date = $conn->real_escape_string($end_date);
+    
     $sql = "SELECT COUNT(id) as new_count 
             FROM customer 
-            WHERE cs_addtime BETWEEN ? AND ?";
+            WHERE cs_addtime BETWEEN '$start_date' AND '$end_date'";
     
-    $stmt = $conn->prepare($sql);
-    $stmt->bind_param("ss", $start_date, $end_date);
-    $stmt->execute();
-    $result = $stmt->get_result();
+    // 如果有业务员过滤
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter) && !empty($employee_filter)) {
+            // 处理数组形式的业务员ID列表
+            $emp_ids = array();
+            foreach ($employee_filter as $emp_id) {
+                if (is_numeric($emp_id)) {
+                    $emp_ids[] = intval($emp_id);
+                }
+            }
+            if (!empty($emp_ids)) {
+                $emp_ids_str = implode(',', $emp_ids);
+                $sql .= " AND cs_belong IN ($emp_ids_str)";
+            }
+        } else if (is_numeric($employee_filter) && $employee_filter > 0) {
+            // 处理单个业务员ID
+            $employee_filter = intval($employee_filter);
+            $sql .= " AND cs_belong = $employee_filter";
+        }
+    }
+    
+    $result = $conn->query($sql);
     $row = $result->fetch_assoc();
     return $row['new_count'];
 }
@@ -476,22 +522,46 @@ function getNewCustomers($conn, $start_date, $end_date) {
  * @param mysqli $conn 数据库连接
  * @param string $start_date 开始日期
  * @param string $end_date 结束日期
+ * @param array|int $employee_filter 业务员ID或ID数组,用于过滤数据 (可选)
  * @return float 平均客户价值
  */
-function getAverageCustomerValue($conn, $start_date, $end_date) {
+function getAverageCustomerValue($conn, $start_date, $end_date, $employee_filter = null) {
+    // 使用 mysqli_real_escape_string 防止 SQL 注入
+    $start_date = $conn->real_escape_string($start_date);
+    $end_date = $conn->real_escape_string($end_date);
+    
     $sql = "SELECT AVG(customer_value) as avg_value FROM (
                 SELECT 
                     o.customer_id,
                     SUM(o.total_amount) as customer_value
                 FROM orders o
-                WHERE o.order_date BETWEEN ? AND ?
-                GROUP BY o.customer_id
-            ) as customer_values";
+                JOIN customer c ON o.customer_id = c.id
+                WHERE o.order_date BETWEEN '$start_date' AND '$end_date'";
     
-    $stmt = $conn->prepare($sql);
-    $stmt->bind_param("ss", $start_date, $end_date);
-    $stmt->execute();
-    $result = $stmt->get_result();
+    // 如果有业务员过滤
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter) && !empty($employee_filter)) {
+            // 处理数组形式的业务员ID列表
+            $emp_ids = array();
+            foreach ($employee_filter as $emp_id) {
+                if (is_numeric($emp_id)) {
+                    $emp_ids[] = intval($emp_id);
+                }
+            }
+            if (!empty($emp_ids)) {
+                $emp_ids_str = implode(',', $emp_ids);
+                $sql .= " AND c.cs_belong IN ($emp_ids_str)";
+            }
+        } else if (is_numeric($employee_filter) && $employee_filter > 0) {
+            // 处理单个业务员ID
+            $employee_filter = intval($employee_filter);
+            $sql .= " AND c.cs_belong = $employee_filter";
+        }
+    }
+    
+    $sql .= " GROUP BY o.customer_id) as customer_values";
+    
+    $result = $conn->query($sql);
     $row = $result->fetch_assoc();
     return $row['avg_value'] ? $row['avg_value'] : 0;
 }
@@ -502,22 +572,46 @@ function getAverageCustomerValue($conn, $start_date, $end_date) {
  * @param mysqli $conn 数据库连接
  * @param string $start_date 开始日期
  * @param string $end_date 结束日期
+ * @param array|int $employee_filter 业务员ID或ID数组,用于过滤数据 (可选)
  * @return array 客户留存率数据
  */
-function getCustomerRetentionRate($conn, $start_date, $end_date) {
+function getCustomerRetentionRate($conn, $start_date, $end_date, $employee_filter = null) {
+    // 使用 mysqli_real_escape_string 防止 SQL 注入
+    $start_date = $conn->real_escape_string($start_date);
+    $end_date = $conn->real_escape_string($end_date);
+    
     // 获取之前时间段的客户
     $previous_start = date('Y-m-d', strtotime('-1 year', strtotime($start_date)));
     $previous_end = date('Y-m-d', strtotime('-1 day', strtotime($start_date)));
     
     // 之前时间段的客户ID
-    $prev_sql = "SELECT DISTINCT customer_id 
-                FROM orders 
-                WHERE order_date BETWEEN ? AND ?";
+    $prev_sql = "SELECT DISTINCT o.customer_id 
+                FROM orders o
+                JOIN customer c ON o.customer_id = c.id
+                WHERE o.order_date BETWEEN '$previous_start' AND '$previous_end'";
     
-    $prev_stmt = $conn->prepare($prev_sql);
-    $prev_stmt->bind_param("ss", $previous_start, $previous_end);
-    $prev_stmt->execute();
-    $prev_result = $prev_stmt->get_result();
+    // 如果有业务员过滤
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter) && !empty($employee_filter)) {
+            // 处理数组形式的业务员ID列表
+            $emp_ids = array();
+            foreach ($employee_filter as $emp_id) {
+                if (is_numeric($emp_id)) {
+                    $emp_ids[] = intval($emp_id);
+                }
+            }
+            if (!empty($emp_ids)) {
+                $emp_ids_str = implode(',', $emp_ids);
+                $prev_sql .= " AND c.cs_belong IN ($emp_ids_str)";
+            }
+        } else if (is_numeric($employee_filter) && $employee_filter > 0) {
+            // 处理单个业务员ID
+            $employee_filter = intval($employee_filter);
+            $prev_sql .= " AND c.cs_belong = $employee_filter";
+        }
+    }
+    
+    $prev_result = $conn->query($prev_sql);
     
     $previous_customers = [];
     while ($row = $prev_result->fetch_assoc()) {
@@ -536,15 +630,34 @@ function getCustomerRetentionRate($conn, $start_date, $end_date) {
     }
     
     // 查询当前时间段内,之前客户中再次购买的客户数
-    $current_sql = "SELECT COUNT(DISTINCT customer_id) as retained_count
-                   FROM orders
-                   WHERE order_date BETWEEN ? AND ?
-                   AND customer_id IN (" . implode(',', $previous_customers) . ")";
-    
-    $current_stmt = $conn->prepare($current_sql);
-    $current_stmt->bind_param("ss", $start_date, $end_date);
-    $current_stmt->execute();
-    $current_result = $current_stmt->get_result();
+    $current_sql = "SELECT COUNT(DISTINCT o.customer_id) as retained_count
+                   FROM orders o
+                   JOIN customer c ON o.customer_id = c.id
+                   WHERE o.order_date BETWEEN '$start_date' AND '$end_date'
+                   AND o.customer_id IN (" . implode(',', $previous_customers) . ")";
+    
+    // 如果有业务员过滤
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter) && !empty($employee_filter)) {
+            // 处理数组形式的业务员ID列表
+            $emp_ids = array();
+            foreach ($employee_filter as $emp_id) {
+                if (is_numeric($emp_id)) {
+                    $emp_ids[] = intval($emp_id);
+                }
+            }
+            if (!empty($emp_ids)) {
+                $emp_ids_str = implode(',', $emp_ids);
+                $current_sql .= " AND c.cs_belong IN ($emp_ids_str)";
+            }
+        } else if (is_numeric($employee_filter) && $employee_filter > 0) {
+            // 处理单个业务员ID
+            $employee_filter = intval($employee_filter);
+            $current_sql .= " AND c.cs_belong = $employee_filter";
+        }
+    }
+    
+    $current_result = $conn->query($current_sql);
     $row = $current_result->fetch_assoc();
     
     $retained_count = $row['retained_count'];
@@ -563,26 +676,70 @@ function getCustomerRetentionRate($conn, $start_date, $end_date) {
  * @param mysqli $conn 数据库连接
  * @param string $start_date 开始日期
  * @param string $end_date 结束日期
+ * @param array|int $employee_filter 业务员ID或ID数组,用于过滤数据 (可选)
  * @return array 下单转换率数据
  */
-function getOrderConversionRate($conn, $start_date, $end_date) {
+function getOrderConversionRate($conn, $start_date, $end_date, $employee_filter = null) {
+    // 使用 mysqli_real_escape_string 防止 SQL 注入
+    $start_date = $conn->real_escape_string($start_date);
+    $end_date = $conn->real_escape_string($end_date);
+    
     // 获取指定时间段内总客户数
-    $total_sql = "SELECT COUNT(DISTINCT id) as total_count FROM customer WHERE cs_addtime <= ?";
-    $total_stmt = $conn->prepare($total_sql);
-    $total_stmt->bind_param("s", $end_date);
-    $total_stmt->execute();
-    $total_result = $total_stmt->get_result();
+    $total_sql = "SELECT COUNT(DISTINCT id) as total_count FROM customer WHERE cs_addtime <= '$end_date'";
+    
+    // 如果有业务员过滤
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter) && !empty($employee_filter)) {
+            // 处理数组形式的业务员ID列表
+            $emp_ids = array();
+            foreach ($employee_filter as $emp_id) {
+                if (is_numeric($emp_id)) {
+                    $emp_ids[] = intval($emp_id);
+                }
+            }
+            if (!empty($emp_ids)) {
+                $emp_ids_str = implode(',', $emp_ids);
+                $total_sql .= " AND cs_belong IN ($emp_ids_str)";
+            }
+        } else if (is_numeric($employee_filter) && $employee_filter > 0) {
+            // 处理单个业务员ID
+            $employee_filter = intval($employee_filter);
+            $total_sql .= " AND cs_belong = $employee_filter";
+        }
+    }
+    
+    $total_result = $conn->query($total_sql);
     $total_row = $total_result->fetch_assoc();
     $total_customers = $total_row['total_count'];
     
     // 获取有订单的客户数
-    $order_sql = "SELECT COUNT(DISTINCT customer_id) as order_count 
-                 FROM orders 
-                 WHERE order_date BETWEEN ? AND ?";
-    $order_stmt = $conn->prepare($order_sql);
-    $order_stmt->bind_param("ss", $start_date, $end_date);
-    $order_stmt->execute();
-    $order_result = $order_stmt->get_result();
+    $order_sql = "SELECT COUNT(DISTINCT o.customer_id) as order_count 
+                 FROM orders o
+                 JOIN customer c ON o.customer_id = c.id
+                 WHERE o.order_date BETWEEN '$start_date' AND '$end_date'";
+    
+    // 如果有业务员过滤
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter) && !empty($employee_filter)) {
+            // 处理数组形式的业务员ID列表
+            $emp_ids = array();
+            foreach ($employee_filter as $emp_id) {
+                if (is_numeric($emp_id)) {
+                    $emp_ids[] = intval($emp_id);
+                }
+            }
+            if (!empty($emp_ids)) {
+                $emp_ids_str = implode(',', $emp_ids);
+                $order_sql .= " AND c.cs_belong IN ($emp_ids_str)";
+            }
+        } else if (is_numeric($employee_filter) && $employee_filter > 0) {
+            // 处理单个业务员ID
+            $employee_filter = intval($employee_filter);
+            $order_sql .= " AND c.cs_belong = $employee_filter";
+        }
+    }
+    
+    $order_result = $conn->query($order_sql);
     $order_row = $order_result->fetch_assoc();
     $customers_with_orders = $order_row['order_count'];
     

+ 245 - 31
statistics_order_warnings.php

@@ -10,6 +10,18 @@ if (!isset($_SESSION['employee_id'])) {
     checkLogin();
 }
 
+// 获取当前登录用户信息
+$current_user_id = $_SESSION['employee_id'];
+$current_permission_role = 0;
+
+// 获取当前用户权限角色
+$current_user_id = intval($current_user_id); // 确保是整数
+$query = "SELECT em_permission_role_id FROM employee WHERE id = $current_user_id";
+$result = $conn->query($query);
+if ($result && $row = $result->fetch_assoc()) {
+    $current_permission_role = $row['em_permission_role_id'];
+}
+
 // 获取日期范围参数
 $date_params = getDateRangeParams();
 $current_start_date = $date_params['start_date_sql'];
@@ -19,8 +31,73 @@ $date_range = $date_params['date_range'];
 // 获取选中的业务员ID
 $selected_employee = isset($_GET['employee_id']) ? intval($_GET['employee_id']) : 0;
 
-// 获取所有业务员列表
-$sql_employees = "SELECT id, em_user FROM employee ORDER BY em_user";
+// 确定要显示哪些业务员的数据
+$employee_filter = null;
+
+if ($selected_employee > 0) {
+    // 如果选择了特定业务员,检查当前用户是否有权限查看该业务员的数据
+    $has_permission = false;
+    
+    if ($current_permission_role == 1) {
+        // 管理员可以查看所有业务员
+        $has_permission = true;
+    } else if ($current_permission_role == 2) {
+        // 组长可以查看自己和组员
+        $query = "SELECT id FROM employee WHERE id = $selected_employee AND (id = $current_user_id OR em_role = $current_user_id)";
+        $result = $conn->query($query);
+        $has_permission = ($result && $result->num_rows > 0);
+    } else {
+        // 普通业务员只能查看自己
+        $has_permission = ($selected_employee == $current_user_id);
+    }
+    
+    if ($has_permission) {
+        $employee_filter = $selected_employee;
+    } else {
+        // 如果没有权限,重置为查看自己的数据
+        $selected_employee = $current_user_id;
+        $employee_filter = $current_user_id;
+    }
+} else {
+    // 如果没有选择特定业务员,则按权限显示相应的业务员数据
+    if ($current_permission_role == 1) {
+        // 管理员可以看到所有业务员
+        $employee_filter = null;
+    } else if ($current_permission_role == 2) {
+        // 组长可以看到自己和组员
+        $visible_employees = [];
+        $query = "SELECT id FROM employee WHERE id = $current_user_id OR em_role = $current_user_id";
+        $result = $conn->query($query);
+        
+        if ($result) {
+            while ($row = $result->fetch_assoc()) {
+                $visible_employees[] = intval($row['id']);
+            }
+        }
+        
+        if (!empty($visible_employees)) {
+            $employee_filter = $visible_employees;
+        } else {
+            $employee_filter = $current_user_id;
+        }
+    } else {
+        // 普通业务员只能看到自己
+        $employee_filter = $current_user_id;
+    }
+}
+
+// 获取业务员列表(基于权限)
+$sql_employees = "";
+if ($current_permission_role == 1) {
+    // 管理员可以看到所有业务员
+    $sql_employees = "SELECT id, em_user FROM employee WHERE em_role IS NOT NULL ORDER BY em_user";
+} else if ($current_permission_role == 2) {
+    // 组长可以看到自己和组员
+    $sql_employees = "SELECT id, em_user FROM employee WHERE id = $current_user_id OR em_role = $current_user_id ORDER BY em_user";
+} else {
+    // 普通业务员只能看到自己
+    $sql_employees = "SELECT id, em_user FROM employee WHERE id = $current_user_id";
+}
 $employees_result = $conn->query($sql_employees);
 
 // 计算上一个时间段范围(用于比较)
@@ -62,6 +139,43 @@ include('statistics_header.php');
     <div class="page-header">
         <h1 class="page-title">订单预警系统</h1>
         <p class="page-description">监控订单异常情况,提前预警潜在问题</p>
+        
+        <?php
+        // 获取当前用户角色显示提示信息
+        $role_info = "";
+        
+        if ($current_permission_role == 1) {
+            // 管理员
+            if ($selected_employee > 0) {
+                $employee_name = "";
+                $emp_query = "SELECT em_user FROM employee WHERE id = $selected_employee";
+                $emp_result = $conn->query($emp_query);
+                if ($emp_result && $emp_row = $emp_result->fetch_assoc()) {
+                    $employee_name = $emp_row['em_user'];
+                    $role_info = "您正在查看业务员 {$employee_name} 的数据";
+                }
+            } else {
+                $role_info = "您正在查看所有业务员的数据";
+            }
+        } else if ($current_permission_role == 2) {
+            // 组长
+            if ($selected_employee > 0 && $selected_employee != $current_user_id) {
+                $employee_name = "";
+                $emp_query = "SELECT em_user FROM employee WHERE id = $selected_employee";
+                $emp_result = $conn->query($emp_query);
+                if ($emp_result && $emp_row = $emp_result->fetch_assoc()) {
+                    $employee_name = $emp_row['em_user'];
+                    $role_info = "您正在查看业务员 {$employee_name} 的数据";
+                }
+            } else if ($selected_employee == 0 || $selected_employee == $current_user_id) {
+                $role_info = "您正在查看您的团队数据";
+            }
+        } else {
+            // 普通业务员
+            $role_info = "您正在查看自己的数据";
+        }
+        ?>
+        <div class="role-info"><?php echo $role_info; ?></div>
     </div>
     
     <!-- 日期筛选 -->
@@ -91,7 +205,7 @@ include('statistics_header.php');
                 <select class="form-control" id="employee_id" name="employee_id">
                     <option value="0">全部业务员</option>
                     <?php while ($emp = $employees_result->fetch_assoc()): ?>
-                    <option value="<?php echo $emp['id']; ?>" <?php echo $selected_employee == $emp['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($emp['em_user']); ?></option>
+                    <option value="<?php echo $emp['id']; ?>" <?php echo $selected_employee == $emp['id'] ? 'selected' : ''; ?>><?php echo htmlspecialcharsFix($emp['em_user']); ?></option>
                     <?php endwhile; ?>
                 </select>
             </div>
@@ -116,17 +230,58 @@ include('statistics_header.php');
             $result = $stmt->get_result();
             $warning_count = $result->fetch_assoc();
             
-            // 获取订单金额下降的客户数
-            $decreasing_amount_count = getDecreasingOrderAmountCustomers($conn, $current_start_date, $current_end_date, $previous_start_date, $previous_end_date, $order_amount_decrease_threshold, true, $selected_employee);
+            // 获取订单金额下降的客户数 - 使用当前用户的筛选条件
+            $query_employee_filter = null;
+            if (is_array($employee_filter) && !empty($employee_filter)) {
+                // 如果是组长查看团队,转换为SQL中的IN条件
+                $query_employee_filter = implode(',', $employee_filter);
+            } else if (!is_array($employee_filter) && $employee_filter > 0) {
+                // 如果是查看单个业务员
+                $query_employee_filter = $employee_filter;
+            }
+            
+            $decreasing_amount_count = getDecreasingOrderAmountCustomers(
+                $conn, 
+                $current_start_date, 
+                $current_end_date, 
+                $previous_start_date, 
+                $previous_end_date, 
+                $order_amount_decrease_threshold, 
+                true, 
+                $query_employee_filter
+            );
             
             // 获取复购周期异常(3个月内未录入订单)的客户数
-            $abnormal_cycle_count = getAbnormalRepurchaseCycleCustomers($conn, $current_start_date, $current_end_date, $repurchase_cycle_threshold, true, $selected_employee);
+            $abnormal_cycle_count = getAbnormalRepurchaseCycleCustomers(
+                $conn, 
+                $current_start_date, 
+                $current_end_date, 
+                $repurchase_cycle_threshold, 
+                true, 
+                $query_employee_filter
+            );
             
             // 获取长期不活跃(3个月内没有客户信息修改)客户数
-            $inactive_customers_count = getInactiveCustomers($conn, $current_end_date, $inactive_threshold, true, 1, 10, $selected_employee);
+            $inactive_customers_count = getInactiveCustomers(
+                $conn, 
+                $current_end_date, 
+                $inactive_threshold, 
+                true, 
+                1, 
+                10, 
+                $query_employee_filter
+            );
             
             // 获取流失客户(1年内未录入订单)数
-            $churn_customers_count = getChurnCustomers($conn, $current_end_date, $churn_threshold, true, 1, 10, $selected_employee);
+            $churn_customers_count = getChurnCustomers(
+                $conn, 
+                $current_end_date, 
+                $churn_threshold, 
+                true, 
+                1, 
+                10, 
+                $query_employee_filter
+            );
             ?>
             
             <div class="col-md-3">
@@ -192,7 +347,7 @@ include('statistics_header.php');
                     $previous_end_date, 
                     $order_amount_decrease_threshold,
                     false,
-                    $selected_employee
+                    $query_employee_filter
                 );
                 
                 while ($customer = $decreasing_customers->fetch_assoc()) {
@@ -200,12 +355,12 @@ include('statistics_header.php');
                     $change_class = $change_percent < -20 ? 'text-danger' : 'text-warning';
                     
                     echo "<tr>";
-                    echo "<td>" . htmlspecialchars($customer['cs_company']) . "</td>";
+                    echo "<td>" . htmlspecialcharsFix($customer['cs_company']) . "</td>";
                     echo "<td>¥" . number_format($customer['current_amount'], 2) . "</td>";
                     echo "<td>¥" . number_format($customer['previous_amount'], 2) . "</td>";
                     echo "<td class='{$change_class}'>" . $change_percent . "%</td>";
                     echo "<td>" . $customer['last_order_date'] . "</td>";
-                    echo "<td>" . htmlspecialchars($customer['em_user']) . "</td>";
+                    echo "<td>" . htmlspecialcharsFix($customer['em_user']) . "</td>";
                     echo "<td><a href='customer_detail.php?id=" . $customer['id'] . "&from_warning=1' class='action-btn action-btn-view'>查看</a></td>";
                     echo "</tr>";
                 }
@@ -245,7 +400,7 @@ include('statistics_header.php');
                 $abnormal_page_size = 10; // 每页显示10条记录
                 
                 // 获取总记录数
-                $total_abnormal = getAbnormalRepurchaseCycleCustomers($conn, $current_start_date, $current_end_date, $repurchase_cycle_threshold, true, $selected_employee);
+                $total_abnormal = getAbnormalRepurchaseCycleCustomers($conn, $current_start_date, $current_end_date, $repurchase_cycle_threshold, true, $query_employee_filter);
                 
                 // 计算总页数
                 $abnormal_total_pages = ceil($total_abnormal / $abnormal_page_size);
@@ -261,7 +416,7 @@ include('statistics_header.php');
                     $current_end_date, 
                     $repurchase_cycle_threshold, 
                     false,
-                    $selected_employee,
+                    $query_employee_filter,
                     $abnormal_page,
                     $abnormal_page_size
                 );
@@ -271,13 +426,13 @@ include('statistics_header.php');
                     $inactive_class = $inactive_days > 60 ? 'text-danger' : 'text-warning';
                     
                     echo "<tr>";
-                    echo "<td title='{$customer['cs_code']}'>" . htmlspecialchars($customer['cs_code']) . "</td>";
-                    echo "<td>" . htmlspecialchars($customer['cs_company'] ?: '未填写') . "</td>";
+                    echo "<td title='{$customer['cs_code']}'>" . htmlspecialcharsFix($customer['cs_code']) . "</td>";
+                    echo "<td>" . htmlspecialcharsFix($customer['cs_company'] ?: '未填写') . "</td>";
                     echo "<td>" . ($customer['last_order_date'] ? $customer['last_order_date'] : '从未下单') . "</td>";
                     echo "<td class='{$inactive_class}'>" . $inactive_days . "</td>";
                     echo "<td>" . $customer['order_count'] . "</td>";
                     echo "<td>¥" . number_format($customer['total_amount'], 2) . "</td>";
-                    echo "<td>" . htmlspecialchars($customer['em_user']) . "</td>";
+                    echo "<td>" . htmlspecialcharsFix($customer['em_user']) . "</td>";
                     echo "<td><a href='customer_detail.php?id=" . $customer['id'] . "&from_warning=1' class='action-btn action-btn-view'>查看</a></td>";
                     echo "</tr>";
                 }
@@ -377,7 +532,7 @@ include('statistics_header.php');
                 $page_size = 10; // 每页显示10条记录
                 
                 // 获取总记录数
-                $total_churn = getChurnCustomers($conn, $current_end_date, $churn_threshold, true, 1, 10, $selected_employee);
+                $total_churn = getChurnCustomers($conn, $current_end_date, $churn_threshold, true, 1, 10, $query_employee_filter);
                 
                 // 计算总页数
                 $total_pages = ceil($total_churn / $page_size);
@@ -387,20 +542,20 @@ include('statistics_header.php');
                 if ($page > $total_pages && $total_pages > 0) $page = $total_pages;
                 
                 // 获取当页数据
-                $churn_customers = getChurnCustomers($conn, $current_end_date, $churn_threshold, false, $page, $page_size, $selected_employee);
+                $churn_customers = getChurnCustomers($conn, $current_end_date, $churn_threshold, false, $page, $page_size, $query_employee_filter);
                 
                 while ($customer = $churn_customers->fetch_assoc()) {
                     $inactive_days = $customer['inactive_days'];
                     $inactive_class = $inactive_days > 365 ? 'text-danger' : 'text-warning';
                     
                     echo "<tr>";
-                    echo "<td title='{$customer['cs_code']}'>" . htmlspecialchars($customer['cs_code']) . "</td>";
-                    echo "<td>" . htmlspecialchars($customer['cs_company'] ?: '未填写') . "</td>";
+                    echo "<td title='{$customer['cs_code']}'>" . htmlspecialcharsFix($customer['cs_code']) . "</td>";
+                    echo "<td>" . htmlspecialcharsFix($customer['cs_company'] ?: '未填写') . "</td>";
                     echo "<td>" . ($customer['last_order_date'] ? $customer['last_order_date'] : '从未下单') . "</td>";
                     echo "<td class='{$inactive_class}'>" . $inactive_days . "</td>";
                     echo "<td>" . $customer['order_count'] . "</td>";
                     echo "<td>¥" . number_format($customer['total_amount'], 2) . "</td>";
-                    echo "<td>" . htmlspecialchars($customer['em_user']) . "</td>";
+                    echo "<td>" . htmlspecialcharsFix($customer['em_user']) . "</td>";
                     echo "<td><a href='customer_detail.php?id=" . $customer['id'] . "&from_warning=1' class='action-btn action-btn-view'>查看</a></td>";
                     echo "</tr>";
                 }
@@ -490,13 +645,29 @@ include('statistics_header.php');
             DATE_FORMAT(order_date, '%Y-%m') as month,
             COUNT(*) as order_count,
             SUM(total_amount) as total_amount
-        FROM orders
-        WHERE order_date >= DATE_SUB(?, INTERVAL 11 MONTH)
-        GROUP BY DATE_FORMAT(order_date, '%Y-%m')
-        ORDER BY month";
+        FROM orders o
+        JOIN customer c ON o.customer_id = c.id
+        WHERE order_date >= DATE_SUB(?, INTERVAL 11 MONTH)";
+        
+        // 添加业务员筛选条件
+        if (is_array($query_employee_filter) && !empty($query_employee_filter)) {
+            // 如果是组长查看团队数据
+            $sql_trend .= " AND c.cs_belong IN (" . $query_employee_filter . ")";
+        } else if (!is_array($query_employee_filter) && $query_employee_filter > 0) {
+            // 如果是查看单个业务员数据
+            $sql_trend .= " AND c.cs_belong = ?";
+        }
+        
+        $sql_trend .= " GROUP BY DATE_FORMAT(order_date, '%Y-%m') ORDER BY month";
         
         $stmt = $conn->prepare($sql_trend);
-        $stmt->bind_param("s", $current_end_date);
+        
+        if (!is_array($query_employee_filter) && $query_employee_filter > 0) {
+            $stmt->bind_param("si", $current_end_date, $query_employee_filter);
+        } else {
+            $stmt->bind_param("s", $current_end_date);
+        }
+        
         $stmt->execute();
         $trend_result = $stmt->get_result();
         
@@ -532,7 +703,14 @@ include('statistics_header.php');
 
 .page-description {
     color: #666;
-    margin-bottom: 0;
+    margin-bottom: 5px;
+}
+
+.role-info {
+    color: #2196f3;
+    font-size: 14px;
+    margin-top: 5px;
+    font-weight: 500;
 }
 
 .filter-form {
@@ -955,7 +1133,16 @@ document.addEventListener('DOMContentLoaded', function() {
  */
 function getDecreasingOrderAmountCustomers($conn, $current_start, $current_end, $previous_start, $previous_end, $threshold, $count_only = false, $selected_employee = 0) {
     // 构建业务员筛选条件
-    $employee_filter = $selected_employee > 0 ? " AND c.cs_belong = " . intval($selected_employee) : "";
+    $employee_filter = "";
+    if (!empty($selected_employee)) {
+        if (is_numeric($selected_employee)) {
+            // 单个业务员
+            $employee_filter = " AND c.cs_belong = " . intval($selected_employee);
+        } else if (strpos($selected_employee, ',') !== false) {
+            // 多个业务员(逗号分隔的字符串)
+            $employee_filter = " AND c.cs_belong IN (" . $selected_employee . ")";
+        }
+    }
     
     // 如果只需要计数
     if ($count_only) {
@@ -1018,7 +1205,16 @@ function getDecreasingOrderAmountCustomers($conn, $current_start, $current_end,
  */
 function getAbnormalRepurchaseCycleCustomers($conn, $current_start, $current_end, $threshold, $count_only = false, $selected_employee = 0, $page = 1, $page_size = 10) {
     // 构建业务员筛选条件
-    $employee_filter = $selected_employee > 0 ? " AND c.cs_belong = " . intval($selected_employee) : "";
+    $employee_filter = "";
+    if (!empty($selected_employee)) {
+        if (is_numeric($selected_employee)) {
+            // 单个业务员
+            $employee_filter = " AND c.cs_belong = " . intval($selected_employee);
+        } else if (strpos($selected_employee, ',') !== false) {
+            // 多个业务员(逗号分隔的字符串)
+            $employee_filter = " AND c.cs_belong IN (" . $selected_employee . ")";
+        }
+    }
     
     if ($count_only) {
         $sql = "SELECT COUNT(DISTINCT c.id) as count
@@ -1082,7 +1278,16 @@ function getAbnormalRepurchaseCycleCustomers($conn, $current_start, $current_end
  */
 function getInactiveCustomers($conn, $end_date, $inactive_days, $count_only = false, $page = 1, $page_size = 10, $selected_employee = 0) {
     // 构建业务员筛选条件
-    $employee_filter = $selected_employee > 0 ? " AND c.cs_belong = " . intval($selected_employee) : "";
+    $employee_filter = "";
+    if (!empty($selected_employee)) {
+        if (is_numeric($selected_employee)) {
+            // 单个业务员
+            $employee_filter = " AND c.cs_belong = " . intval($selected_employee);
+        } else if (strpos($selected_employee, ',') !== false) {
+            // 多个业务员(逗号分隔的字符串)
+            $employee_filter = " AND c.cs_belong IN (" . $selected_employee . ")";
+        }
+    }
     
     if ($count_only) {
         $sql = "SELECT COUNT(*) as count
@@ -1133,7 +1338,16 @@ function getInactiveCustomers($conn, $end_date, $inactive_days, $count_only = fa
  */
 function getChurnCustomers($conn, $end_date, $churn_days, $count_only = false, $page = 1, $page_size = 10, $selected_employee = 0) {
     // 构建业务员筛选条件
-    $employee_filter = $selected_employee > 0 ? " AND c.cs_belong = " . intval($selected_employee) : "";
+    $employee_filter = "";
+    if (!empty($selected_employee)) {
+        if (is_numeric($selected_employee)) {
+            // 单个业务员
+            $employee_filter = " AND c.cs_belong = " . intval($selected_employee);
+        } else if (strpos($selected_employee, ',') !== false) {
+            // 多个业务员(逗号分隔的字符串)
+            $employee_filter = " AND c.cs_belong IN (" . $selected_employee . ")";
+        }
+    }
     
     if ($count_only) {
         $sql = "SELECT COUNT(*) as count

+ 415 - 110
statistics_products.php

@@ -14,25 +14,42 @@ require_once 'statistics_utils.php';
  * @param string $start_date 开始日期
  * @param string $end_date 结束日期
  * @param int $limit 限制返回的产品数量
+ * @param mixed $employee_filter 业务员过滤条件
  * @return mysqli_result 热门产品数据结果集
  */
-function getTopProducts($conn, $start_date, $end_date, $limit = 5) {
+function getTopProducts($conn, $start_date, $end_date, $limit = 5, $employee_filter = null) {
     $sql = "SELECT 
                 p.ProductName, 
                 SUM(oi.quantity) as total_quantity,
                 SUM(oi.total_price) as total_revenue
             FROM order_items oi
             JOIN products p ON oi.product_id = p.id
-            JOIN orders o ON oi.order_id = o.id
-            WHERE o.order_date BETWEEN ? AND ?
-            GROUP BY oi.product_id
+            JOIN orders o ON oi.order_id = o.id";
+    
+    if ($employee_filter !== null) {
+        $sql .= " JOIN customer c ON o.customer_id = c.id";
+    }
+    
+    $sql .= " WHERE o.order_date BETWEEN '$start_date' AND '$end_date'";
+    
+    // 添加业务员过滤
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (count($employee_filter) > 0) {
+                $employee_ids = implode(',', $employee_filter);
+                $sql .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql .= " AND c.cs_belong = $employee_filter";
+        }
+    }
+    
+    $sql .= " GROUP BY oi.product_id
             ORDER BY total_revenue DESC
-            LIMIT ?";
+            LIMIT $limit";
     
-    $stmt = $conn->prepare($sql);
-    $stmt->bind_param("ssi", $start_date, $end_date, $limit);
-    $stmt->execute();
-    return $stmt->get_result();
+    $result = $conn->query($sql);
+    return $result;
 }
 
 /**
@@ -43,9 +60,10 @@ function getTopProducts($conn, $start_date, $end_date, $limit = 5) {
  * @param string $end_date 结束日期
  * @param int $product_id 产品ID,为0时获取所有产品的总体趋势
  * @param string $period 时间粒度 (day/week/month)
+ * @param mixed $employee_filter 业务员过滤条件
  * @return mysqli_result 产品销售趋势数据结果集
  */
-function getProductSalesTrend($conn, $start_date, $end_date, $product_id = 0, $period = 'month') {
+function getProductSalesTrend($conn, $start_date, $end_date, $product_id = 0, $period = 'month', $employee_filter = null) {
     $groupFormat = '%Y-%m-%d';
     if ($period == 'week') {
         $groupFormat = '%x-W%v'; // ISO year and week number
@@ -61,25 +79,33 @@ function getProductSalesTrend($conn, $start_date, $end_date, $product_id = 0, $p
             FROM order_items oi
             JOIN orders o ON oi.order_id = o.id";
     
-    if ($product_id > 0) {
-        $sql .= " WHERE o.order_date BETWEEN ? AND ? AND oi.product_id = ?";
-    } else {
-        $sql .= " WHERE o.order_date BETWEEN ? AND ?";
+    if ($employee_filter !== null) {
+        $sql .= " JOIN customer c ON o.customer_id = c.id";
     }
     
-    $sql .= " GROUP BY time_period
-              ORDER BY MIN(o.order_date)";
-    
-    $stmt = $conn->prepare($sql);
+    $sql .= " WHERE o.order_date BETWEEN '$start_date' AND '$end_date'";
     
     if ($product_id > 0) {
-        $stmt->bind_param("ssi", $start_date, $end_date, $product_id);
-    } else {
-        $stmt->bind_param("ss", $start_date, $end_date);
+        $sql .= " AND oi.product_id = $product_id";
     }
     
-    $stmt->execute();
-    return $stmt->get_result();
+    // 添加业务员过滤
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (count($employee_filter) > 0) {
+                $employee_ids = implode(',', $employee_filter);
+                $sql .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql .= " AND c.cs_belong = $employee_filter";
+        }
+    }
+    
+    $sql .= " GROUP BY time_period
+              ORDER BY MIN(o.order_date)";
+    
+    $result = $conn->query($sql);
+    return $result;
 }
 
 /**
@@ -88,9 +114,10 @@ function getProductSalesTrend($conn, $start_date, $end_date, $product_id = 0, $p
  * @param mysqli $conn 数据库连接
  * @param string $start_date 开始日期
  * @param string $end_date 结束日期
+ * @param mixed $employee_filter 业务员过滤条件
  * @return mysqli_result 产品类别销售分布数据结果集
  */
-function getProductCategorySales($conn, $start_date, $end_date) {
+function getProductCategorySales($conn, $start_date, $end_date, $employee_filter = null) {
     $sql = "SELECT 
                 pc.name as category_name, 
                 SUM(oi.quantity) as total_quantity,
@@ -99,15 +126,31 @@ function getProductCategorySales($conn, $start_date, $end_date) {
             FROM order_items oi
             JOIN products p ON oi.product_id = p.id
             JOIN product_categories pc ON p.category_id = pc.id
-            JOIN orders o ON oi.order_id = o.id
-            WHERE o.order_date BETWEEN ? AND ?
-            GROUP BY p.category_id
+            JOIN orders o ON oi.order_id = o.id";
+    
+    if ($employee_filter !== null) {
+        $sql .= " JOIN customer c ON o.customer_id = c.id";
+    }
+    
+    $sql .= " WHERE o.order_date BETWEEN '$start_date' AND '$end_date'";
+    
+    // 添加业务员过滤
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (count($employee_filter) > 0) {
+                $employee_ids = implode(',', $employee_filter);
+                $sql .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql .= " AND c.cs_belong = $employee_filter";
+        }
+    }
+    
+    $sql .= " GROUP BY p.category_id
             ORDER BY total_revenue DESC";
     
-    $stmt = $conn->prepare($sql);
-    $stmt->bind_param("ss", $start_date, $end_date);
-    $stmt->execute();
-    return $stmt->get_result();
+    $result = $conn->query($sql);
+    return $result;
 }
 
 /**
@@ -116,10 +159,11 @@ function getProductCategorySales($conn, $start_date, $end_date) {
  * @param mysqli $conn 数据库连接
  * @param string $start_date 开始日期
  * @param string $end_date 结束日期
+ * @param mixed $employee_filter 业务员过滤条件
  * @param int $limit 限制返回的产品-地区组合数量
  * @return mysqli_result 产品与地区关联分析数据结果集
  */
-function getProductRegionAnalysis($conn, $start_date, $end_date, $limit = 10) {
+function getProductRegionAnalysis($conn, $start_date, $end_date, $employee_filter = null, $limit = 10) {
     $sql = "SELECT 
                 p.ProductName, 
                 c.countryName,
@@ -129,28 +173,45 @@ function getProductRegionAnalysis($conn, $start_date, $end_date, $limit = 10) {
             JOIN products p ON oi.product_id = p.id
             JOIN orders o ON oi.order_id = o.id
             JOIN customer cu ON o.customer_id = cu.id
-            JOIN country c ON cu.cs_country = c.id
-            WHERE o.order_date BETWEEN ? AND ?
-            GROUP BY oi.product_id, cu.cs_country
+            JOIN country c ON cu.cs_country = c.id";
+    
+    $sql .= " WHERE o.order_date BETWEEN '$start_date' AND '$end_date'";
+    
+    // 添加业务员过滤
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (count($employee_filter) > 0) {
+                $employee_ids = implode(',', $employee_filter);
+                $sql .= " AND cu.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql .= " AND cu.cs_belong = $employee_filter";
+        }
+    }
+    
+    $sql .= " GROUP BY oi.product_id, cu.cs_country
             ORDER BY total_revenue DESC
-            LIMIT ?";
+            LIMIT $limit";
     
-    $stmt = $conn->prepare($sql);
-    $stmt->bind_param("ssi", $start_date, $end_date, $limit);
-    $stmt->execute();
-    return $stmt->get_result();
+    $result = $conn->query($sql);
+    return $result;
 }
 
 /**
  * 获取产品销售概览数据
+ * 
+ * @param mysqli $conn 数据库连接
+ * @param string $start_date 开始日期
+ * @param string $end_date 结束日期
+ * @param int $category_filter 产品分类过滤
+ * @param mixed $employee_filter 业务员过滤条件
+ * @return array 产品销售概览数据
  */
-function getProductSalesOverview($conn, $start_date, $end_date, $category_filter = 0) {
-    $where_clause = "WHERE o.order_date BETWEEN ? AND ?";
-    $params = [$start_date, $end_date];
+function getProductSalesOverview($conn, $start_date, $end_date, $category_filter = 0, $employee_filter = null) {
+    $where_clause = "WHERE o.order_date BETWEEN '$start_date' AND '$end_date'";
     
     if ($category_filter > 0) {
-        $where_clause .= " AND p.category_id = ?";
-        $params[] = $category_filter;
+        $where_clause .= " AND p.category_id = $category_filter";
     }
     
     $sql = "SELECT 
@@ -163,19 +224,42 @@ function getProductSalesOverview($conn, $start_date, $end_date, $category_filter
                 COUNT(DISTINCT o.customer_id) as total_customers
             FROM order_items oi
             JOIN orders o ON oi.order_id = o.id
-            JOIN products p ON oi.product_id = p.id
-            $where_clause";
+            JOIN products p ON oi.product_id = p.id";
     
-    $stmt = $conn->prepare($sql);
-    $stmt->bind_param(str_repeat('s', count($params)), ...$params);
-    $stmt->execute();
-    return $stmt->get_result()->fetch_assoc();
+    if ($employee_filter !== null) {
+        $sql .= " JOIN customer c ON o.customer_id = c.id";
+    }
+    
+    $sql .= " $where_clause";
+    
+    // 添加业务员过滤
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (count($employee_filter) > 0) {
+                $employee_ids = implode(',', $employee_filter);
+                $sql .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql .= " AND c.cs_belong = $employee_filter";
+        }
+    }
+    
+    $result = $conn->query($sql);
+    return $result->fetch_assoc();
 }
 
 /**
  * 获取产品价格趋势分析
+ * 
+ * @param mysqli $conn 数据库连接
+ * @param string $start_date 开始日期
+ * @param string $end_date 结束日期
+ * @param int $product_id 产品ID
+ * @param string $period 时间粒度
+ * @param mixed $employee_filter 业务员过滤条件
+ * @return mysqli_result 产品价格趋势数据
  */
-function getProductPriceTrendAnalysis($conn, $start_date, $end_date, $product_id = 0, $period = 'month') {
+function getProductPriceTrendAnalysis($conn, $start_date, $end_date, $product_id = 0, $period = 'month', $employee_filter = null) {
     $groupFormat = getPeriodFormat($period);
     
     $sql = "SELECT 
@@ -186,28 +270,45 @@ function getProductPriceTrendAnalysis($conn, $start_date, $end_date, $product_id
             FROM order_items oi
             JOIN orders o ON oi.order_id = o.id";
     
-    if ($product_id > 0) {
-        $sql .= " WHERE o.order_date BETWEEN ? AND ? AND oi.product_id = ?";
-    } else {
-        $sql .= " WHERE o.order_date BETWEEN ? AND ?";
+    if ($employee_filter !== null) {
+        $sql .= " JOIN customer c ON o.customer_id = c.id";
     }
     
-    $sql .= " GROUP BY time_period ORDER BY MIN(o.order_date)";
+    $sql .= " WHERE o.order_date BETWEEN '$start_date' AND '$end_date'";
     
-    $stmt = $conn->prepare($sql);
     if ($product_id > 0) {
-        $stmt->bind_param("ssi", $start_date, $end_date, $product_id);
-    } else {
-        $stmt->bind_param("ss", $start_date, $end_date);
+        $sql .= " AND oi.product_id = $product_id";
     }
-    $stmt->execute();
-    return $stmt->get_result();
+    
+    // 添加业务员过滤
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (count($employee_filter) > 0) {
+                $employee_ids = implode(',', $employee_filter);
+                $sql .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql .= " AND c.cs_belong = $employee_filter";
+        }
+    }
+    
+    $sql .= " GROUP BY time_period ORDER BY MIN(o.order_date)";
+    
+    $result = $conn->query($sql);
+    return $result;
 }
 
 /**
  * 获取产品季节性分析
+ * 
+ * @param mysqli $conn 数据库连接
+ * @param string $start_date 开始日期
+ * @param string $end_date 结束日期
+ * @param int $product_id 产品ID
+ * @param mixed $employee_filter 业务员过滤条件
+ * @return mysqli_result 产品季节性分析数据
  */
-function getProductSeasonalityAnalysis($conn, $start_date, $end_date, $product_id = 0) {
+function getProductSeasonalityAnalysis($conn, $start_date, $end_date, $product_id = 0, $employee_filter = null) {
     $sql = "SELECT 
                 MONTH(o.order_date) as month,
                 SUM(oi.quantity) as total_quantity,
@@ -216,29 +317,46 @@ function getProductSeasonalityAnalysis($conn, $start_date, $end_date, $product_i
             FROM order_items oi
             JOIN orders o ON oi.order_id = o.id";
     
+    if ($employee_filter !== null) {
+        $sql .= " JOIN customer c ON o.customer_id = c.id";
+    }
+    
+    $sql .= " WHERE o.order_date BETWEEN '$start_date' AND '$end_date'";
+    
     if ($product_id > 0) {
-        $sql .= " WHERE oi.product_id = ? AND o.order_date BETWEEN ? AND ?";
-    } else {
-        $sql .= " WHERE o.order_date BETWEEN ? AND ?";
+        $sql .= " AND oi.product_id = $product_id";
+    }
+    
+    // 添加业务员过滤
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (count($employee_filter) > 0) {
+                $employee_ids = implode(',', $employee_filter);
+                $sql .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql .= " AND c.cs_belong = $employee_filter";
+        }
     }
     
     $sql .= " GROUP BY MONTH(o.order_date)
               ORDER BY MONTH(o.order_date)";
     
-    $stmt = $conn->prepare($sql);
-    if ($product_id > 0) {
-        $stmt->bind_param("iss", $product_id, $start_date, $end_date);
-    } else {
-        $stmt->bind_param("ss", $start_date, $end_date);
-    }
-    $stmt->execute();
-    return $stmt->get_result();
+    $result = $conn->query($sql);
+    return $result;
 }
 
 /**
  * 获取产品客户细分分析
+ * 
+ * @param mysqli $conn 数据库连接
+ * @param string $start_date 开始日期
+ * @param string $end_date 结束日期
+ * @param int $product_id 产品ID
+ * @param mixed $employee_filter 业务员过滤条件
+ * @return mysqli_result 产品客户细分分析数据
  */
-function getProductCustomerSegmentAnalysis($conn, $start_date, $end_date, $product_id = 0) {
+function getProductCustomerSegmentAnalysis($conn, $start_date, $end_date, $product_id = 0, $employee_filter = null) {
     $sql = "SELECT 
                 ct.businessType as segment_name,
                 COUNT(DISTINCT o.customer_id) as customer_count,
@@ -250,22 +368,28 @@ function getProductCustomerSegmentAnalysis($conn, $start_date, $end_date, $produ
             JOIN customer c ON o.customer_id = c.id
             JOIN clienttype ct ON c.cs_type = ct.id";
     
+    $sql .= " WHERE o.order_date BETWEEN '$start_date' AND '$end_date'";
+    
     if ($product_id > 0) {
-        $sql .= " WHERE oi.product_id = ? AND o.order_date BETWEEN ? AND ?";
-    } else {
-        $sql .= " WHERE o.order_date BETWEEN ? AND ?";
+        $sql .= " AND oi.product_id = $product_id";
+    }
+    
+    // 添加业务员过滤
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (count($employee_filter) > 0) {
+                $employee_ids = implode(',', $employee_filter);
+                $sql .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql .= " AND c.cs_belong = $employee_filter";
+        }
     }
     
     $sql .= " GROUP BY ct.id";
     
-    $stmt = $conn->prepare($sql);
-    if ($product_id > 0) {
-        $stmt->bind_param("iss", $product_id, $start_date, $end_date);
-    } else {
-        $stmt->bind_param("ss", $start_date, $end_date);
-    }
-    $stmt->execute();
-    return $stmt->get_result();
+    $result = $conn->query($sql);
+    return $result;
 }
 
 /**
@@ -917,8 +1041,15 @@ function renderProductCustomerSegmentChart($segment_data) {
 
 /**
  * 获取产品增长率分析
+ * 
+ * @param mysqli $conn 数据库连接
+ * @param string $start_date 开始日期
+ * @param string $end_date 结束日期
+ * @param string $period 时间粒度
+ * @param mixed $employee_filter 业务员过滤条件
+ * @return array 产品增长率分析数据
  */
-function getProductGrowthAnalysis($conn, $start_date, $end_date, $period = 'month') {
+function getProductGrowthAnalysis($conn, $start_date, $end_date, $period = 'month', $employee_filter = null) {
     $groupFormat = getPeriodFormat($period);
     
     // 获取当前期间的数据
@@ -929,17 +1060,32 @@ function getProductGrowthAnalysis($conn, $start_date, $end_date, $period = 'mont
                 COUNT(DISTINCT o.id) as current_orders
             FROM order_items oi
             JOIN products p ON oi.product_id = p.id
-            JOIN orders o ON oi.order_id = o.id
-            WHERE o.order_date BETWEEN ? AND ?
-            GROUP BY oi.product_id
+            JOIN orders o ON oi.order_id = o.id";
+    
+    if ($employee_filter !== null) {
+        $sql .= " JOIN customer c ON o.customer_id = c.id";
+    }
+    
+    $sql .= " WHERE o.order_date BETWEEN '$start_date' AND '$end_date'";
+    
+    // 添加业务员过滤
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (count($employee_filter) > 0) {
+                $employee_ids = implode(',', $employee_filter);
+                $sql .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql .= " AND c.cs_belong = $employee_filter";
+        }
+    }
+    
+    $sql .= " GROUP BY oi.product_id
             HAVING current_revenue > 0
             ORDER BY current_revenue DESC
             LIMIT 10";
     
-    $stmt = $conn->prepare($sql);
-    $stmt->bind_param("ss", $start_date, $end_date);
-    $stmt->execute();
-    $current_data = $stmt->get_result();
+    $current_data = $conn->query($sql);
     
     // 计算上一个时间段
     $date1 = new DateTime($start_date);
@@ -959,13 +1105,10 @@ function getProductGrowthAnalysis($conn, $start_date, $end_date, $period = 'mont
             FROM order_items oi
             JOIN products p ON oi.product_id = p.id
             JOIN orders o ON oi.order_id = o.id
-            WHERE o.order_date BETWEEN ? AND ?
+            WHERE o.order_date BETWEEN '$prev_start' AND '$prev_end'
             GROUP BY oi.product_id";
     
-    $stmt = $conn->prepare($sql);
-    $stmt->bind_param("ss", $prev_start, $prev_end);
-    $stmt->execute();
-    $prev_result = $stmt->get_result();
+    $prev_result = $conn->query($sql);
     
     $prev_data = [];
     while ($row = $prev_result->fetch_assoc()) {
@@ -1072,8 +1215,14 @@ function renderProductGrowthAnalysis($growth_data) {
 
 /**
  * 获取产品购买频率分析
+ * 
+ * @param mysqli $conn 数据库连接
+ * @param string $start_date 开始日期
+ * @param string $end_date 结束日期
+ * @param mixed $employee_filter 业务员过滤条件
+ * @return mysqli_result 产品购买频率分析数据
  */
-function getProductPurchaseFrequency($conn, $start_date, $end_date) {
+function getProductPurchaseFrequency($conn, $start_date, $end_date, $employee_filter = null) {
     $sql = "SELECT 
                 p.ProductName,
                 COUNT(DISTINCT o.id) as order_count,
@@ -1088,8 +1237,13 @@ function getProductPurchaseFrequency($conn, $start_date, $end_date) {
                 ) as avg_days_between_orders
             FROM order_items oi
             JOIN products p ON oi.product_id = p.id
-            JOIN orders o ON oi.order_id = o.id
-            LEFT JOIN (
+            JOIN orders o ON oi.order_id = o.id";
+    
+    if ($employee_filter !== null) {
+        $sql .= " JOIN customer c ON o.customer_id = c.id";
+    }
+    
+    $sql .= " LEFT JOIN (
                 SELECT 
                     o1.customer_id,
                     o1.order_date,
@@ -1097,20 +1251,31 @@ function getProductPurchaseFrequency($conn, $start_date, $end_date) {
                 FROM orders o1
                 LEFT JOIN orders o2 ON o1.customer_id = o2.customer_id 
                     AND o2.order_date > o1.order_date
-                WHERE o1.order_date BETWEEN ? AND ?
+                WHERE o1.order_date BETWEEN '$start_date' AND '$end_date'
                 GROUP BY o1.customer_id, o1.order_date
             ) next_order ON o.customer_id = next_order.customer_id 
                 AND o.order_date = next_order.order_date
-            WHERE o.order_date BETWEEN ? AND ?
-            GROUP BY p.id
+            WHERE o.order_date BETWEEN '$start_date' AND '$end_date'";
+    
+    // 添加业务员过滤
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (count($employee_filter) > 0) {
+                $employee_ids = implode(',', $employee_filter);
+                $sql .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql .= " AND c.cs_belong = $employee_filter";
+        }
+    }
+    
+    $sql .= " GROUP BY p.id
             HAVING order_count > 1
             ORDER BY purchase_frequency DESC
             LIMIT 10";
             
-    $stmt = $conn->prepare($sql);
-    $stmt->bind_param("ssss", $start_date, $end_date, $start_date, $end_date);
-    $stmt->execute();
-    return $stmt->get_result();
+    $result = $conn->query($sql);
+    return $result;
 }
 
 /**
@@ -1146,4 +1311,144 @@ function renderProductPurchaseFrequency($frequency_data) {
         </table>
     </div>
     <?php
+}
+
+/**
+ * 获取新客户购买产品明细
+ * 
+ * @param mysqli $conn 数据库连接
+ * @param string $start_date 开始日期
+ * @param string $end_date 结束日期
+ * @param int $category_filter 分类过滤
+ * @param mixed $employee_filter 业务员过滤条件
+ * @return array 新客户购买产品明细数据
+ */
+function getNewCustomerProductPurchases($conn, $start_date, $end_date, $category_filter = 0, $employee_filter = null) {
+    // 获取符合条件的新客户订单
+    $sql = "SELECT 
+                p.ProductName,
+                p.id as product_id,
+                pc.name as category_name,
+                COUNT(DISTINCT o.customer_id) as customer_count,
+                COUNT(DISTINCT o.id) as order_count,
+                SUM(oi.quantity) as total_quantity,
+                SUM(oi.total_price) as total_revenue,
+                AVG(oi.unit_price) as avg_unit_price
+            FROM orders o
+            JOIN order_items oi ON o.id = oi.order_id
+            JOIN products p ON oi.product_id = p.id
+            JOIN product_categories pc ON p.category_id = pc.id
+            JOIN customer c ON o.customer_id = c.id
+            WHERE o.order_date BETWEEN '$start_date' AND '$end_date'
+            AND o.id IN (
+                SELECT MIN(id) 
+                FROM orders 
+                WHERE order_date BETWEEN '$start_date' AND '$end_date'";
+    
+    if ($employee_filter !== null) {
+        $sql .= " AND customer_id IN (
+                    SELECT id FROM customer WHERE ";
+        
+        if (is_array($employee_filter)) {
+            if (count($employee_filter) > 0) {
+                $employee_ids = implode(',', $employee_filter);
+                $sql .= "cs_belong IN ($employee_ids))";
+            } else {
+                $sql .= "1=1)";
+            }
+        } else {
+            $sql .= "cs_belong = $employee_filter)";
+        }
+    }
+    
+    $sql .= " GROUP BY customer_id
+            )";
+    
+    if ($category_filter > 0) {
+        $sql .= " AND p.category_id = $category_filter";
+    }
+    
+    // 添加业务员过滤
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (count($employee_filter) > 0) {
+                $employee_ids = implode(',', $employee_filter);
+                $sql .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql .= " AND c.cs_belong = $employee_filter";
+        }
+    }
+    
+    $sql .= " GROUP BY p.id
+              ORDER BY customer_count DESC, total_revenue DESC";
+    
+    $result = $conn->query($sql);
+    
+    // 查询新客户总数
+    $sql_count = "SELECT 
+                    COUNT(DISTINCT o.customer_id) as total_new_customers
+                FROM orders o
+                JOIN customer c ON o.customer_id = c.id
+                WHERE o.order_date BETWEEN '$start_date' AND '$end_date'
+                AND o.id IN (
+                    SELECT MIN(id) 
+                    FROM orders 
+                    WHERE order_date BETWEEN '$start_date' AND '$end_date'";
+    
+    if ($employee_filter !== null) {
+        $sql_count .= " AND customer_id IN (
+                        SELECT id FROM customer WHERE ";
+        
+        if (is_array($employee_filter)) {
+            if (count($employee_filter) > 0) {
+                $employee_ids = implode(',', $employee_filter);
+                $sql_count .= "cs_belong IN ($employee_ids))";
+            } else {
+                $sql_count .= "1=1)";
+            }
+        } else {
+            $sql_count .= "cs_belong = $employee_filter)";
+        }
+    }
+    
+    $sql_count .= " GROUP BY customer_id
+                )";
+    
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter)) {
+            if (count($employee_filter) > 0) {
+                $employee_ids = implode(',', $employee_filter);
+                $sql_count .= " AND c.cs_belong IN ($employee_ids)";
+            }
+        } else {
+            $sql_count .= " AND c.cs_belong = $employee_filter";
+        }
+    }
+    
+    $result_count = $conn->query($sql_count);
+    $count_row = $result_count->fetch_assoc();
+    $new_customer_count = $count_row ? $count_row['total_new_customers'] : 0;
+    
+    // 格式化返回数据
+    $products = [];
+    if ($result) {
+        while ($row = $result->fetch_assoc()) {
+            $products[] = [
+                'product_name' => $row['ProductName'],
+                'product_id' => $row['product_id'],
+                'category_name' => $row['category_name'],
+                'customer_count' => $row['customer_count'],
+                'order_count' => $row['order_count'],
+                'total_quantity' => $row['total_quantity'],
+                'total_revenue' => $row['total_revenue'],
+                'avg_price' => $row['avg_unit_price']
+            ];
+        }
+    }
+    
+    return [
+        'products' => $products,
+        'new_customer_count' => $new_customer_count
+    ];
 }

+ 266 - 13
statistics_region.php

@@ -11,14 +11,39 @@ require_once 'statistics_utils.php';
  * 获取客户国家分布
  * 
  * @param mysqli $conn 数据库连接
+ * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  * @return mysqli_result 客户国家分布数据结果集
  */
-function getCustomerCountryDistribution($conn) {
+function getCustomerCountryDistribution($conn, $employee_filter = null) {
+    $employee_condition = "";
+    
+    // 如果有业务员过滤条件
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter) && !empty($employee_filter)) {
+            // 处理数组形式的业务员ID列表
+            $emp_ids = [];
+            foreach ($employee_filter as $emp_id) {
+                if (is_numeric($emp_id)) {
+                    $emp_ids[] = intval($emp_id);
+                }
+            }
+            if (!empty($emp_ids)) {
+                $emp_ids_str = implode(',', $emp_ids);
+                $employee_condition = " WHERE cu.cs_belong IN ($emp_ids_str)";
+            }
+        } else if (is_numeric($employee_filter) && $employee_filter > 0) {
+            // 处理单个业务员ID
+            $employee_filter = intval($employee_filter);
+            $employee_condition = " WHERE cu.cs_belong = $employee_filter";
+        }
+    }
+    
     $sql = "SELECT 
                 c.countryName, 
                 COUNT(cu.id) as customer_count
             FROM customer cu
             JOIN country c ON cu.cs_country = c.id
+            $employee_condition
             GROUP BY cu.cs_country
             ORDER BY customer_count DESC
             LIMIT 10";
@@ -32,9 +57,35 @@ function getCustomerCountryDistribution($conn) {
  * @param mysqli $conn 数据库连接
  * @param string $start_date 开始日期
  * @param string $end_date 结束日期
+ * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  * @return mysqli_result 地区订单数据结果集
  */
-function getOrdersByRegion($conn, $start_date, $end_date) {
+function getOrdersByRegion($conn, $start_date, $end_date, $employee_filter = null) {
+    $employee_condition = "";
+    $params = [$start_date, $end_date];
+    $types = "ss";
+    
+    // 如果有业务员过滤条件
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter) && !empty($employee_filter)) {
+            // 处理数组形式的业务员ID列表
+            $emp_ids = [];
+            foreach ($employee_filter as $emp_id) {
+                if (is_numeric($emp_id)) {
+                    $emp_ids[] = intval($emp_id);
+                }
+            }
+            if (!empty($emp_ids)) {
+                $emp_ids_str = implode(',', $emp_ids);
+                $employee_condition = " AND cu.cs_belong IN ($emp_ids_str)";
+            }
+        } else if (is_numeric($employee_filter) && $employee_filter > 0) {
+            // 处理单个业务员ID
+            $employee_filter = intval($employee_filter);
+            $employee_condition = " AND cu.cs_belong = $employee_filter";
+        }
+    }
+    
     $sql = "SELECT 
                 c.countryName, 
                 COUNT(o.id) as order_count,
@@ -45,12 +96,13 @@ function getOrdersByRegion($conn, $start_date, $end_date) {
             JOIN country c ON cu.cs_country = c.id
             LEFT JOIN order_items oi ON o.id = oi.order_id
             WHERE o.order_date BETWEEN ? AND ?
+            $employee_condition
             GROUP BY cu.cs_country
             ORDER BY total_quantity DESC
             LIMIT 10";
     
     $stmt = $conn->prepare($sql);
-    $stmt->bind_param("ss", $start_date, $end_date);
+    $stmt->bind_param($types, ...$params);
     $stmt->execute();
     return $stmt->get_result();
 }
@@ -61,9 +113,10 @@ function getOrdersByRegion($conn, $start_date, $end_date) {
  * @param mysqli $conn 数据库连接
  * @param string $current_start 当前周期开始日期
  * @param string $current_end 当前周期结束日期
+ * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  * @return array 地区销售同比环比数据
  */
-function getRegionSalesComparison($conn, $current_start, $current_end) {
+function getRegionSalesComparison($conn, $current_start, $current_end, $employee_filter = null) {
     // 计算上一个相同时长的周期
     $current_start_date = new DateTime($current_start);
     $current_end_date = new DateTime($current_end);
@@ -77,6 +130,29 @@ function getRegionSalesComparison($conn, $current_start, $current_end) {
     $prev_start = $prev_start_date->format('Y-m-d');
     $prev_end = $prev_end_date->format('Y-m-d') . ' 23:59:59';
     
+    // 如果有业务员过滤条件
+    $employee_condition = "";
+    
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter) && !empty($employee_filter)) {
+            // 处理数组形式的业务员ID列表
+            $emp_ids = [];
+            foreach ($employee_filter as $emp_id) {
+                if (is_numeric($emp_id)) {
+                    $emp_ids[] = intval($emp_id);
+                }
+            }
+            if (!empty($emp_ids)) {
+                $emp_ids_str = implode(',', $emp_ids);
+                $employee_condition = " AND cu.cs_belong IN ($emp_ids_str)";
+            }
+        } else if (is_numeric($employee_filter) && $employee_filter > 0) {
+            // 处理单个业务员ID
+            $employee_filter = intval($employee_filter);
+            $employee_condition = " AND cu.cs_belong = $employee_filter";
+        }
+    }
+    
     // 获取当前周期数据
     $sql = "SELECT 
                 c.countryName, 
@@ -86,6 +162,7 @@ function getRegionSalesComparison($conn, $current_start, $current_end) {
             JOIN customer cu ON o.customer_id = cu.id
             JOIN country c ON cu.cs_country = c.id
             WHERE o.order_date BETWEEN ? AND ?
+            $employee_condition
             GROUP BY cu.cs_country
             ORDER BY total_amount DESC
             LIMIT 5";
@@ -329,13 +406,39 @@ function renderRegionSalesComparisonTable($comparison_data) {
  * @param mysqli $conn 数据库连接
  * @param string $start_date 开始日期
  * @param string $end_date 结束日期
+ * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  * @return array 总销售额和增长率
  */
-function getRegionTotalSales($conn, $start_date, $end_date) {
+function getRegionTotalSales($conn, $start_date, $end_date, $employee_filter = null) {
+    // 如果有业务员过滤条件
+    $employee_condition = "";
+    
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter) && !empty($employee_filter)) {
+            // 处理数组形式的业务员ID列表
+            $emp_ids = [];
+            foreach ($employee_filter as $emp_id) {
+                if (is_numeric($emp_id)) {
+                    $emp_ids[] = intval($emp_id);
+                }
+            }
+            if (!empty($emp_ids)) {
+                $emp_ids_str = implode(',', $emp_ids);
+                $employee_condition = " AND cu.cs_belong IN ($emp_ids_str)";
+            }
+        } else if (is_numeric($employee_filter) && $employee_filter > 0) {
+            // 处理单个业务员ID
+            $employee_filter = intval($employee_filter);
+            $employee_condition = " AND cu.cs_belong = $employee_filter";
+        }
+    }
+    
     // 计算当前周期销售额
     $sql = "SELECT SUM(o.total_amount) as total_amount
             FROM orders o
-            WHERE o.order_date BETWEEN ? AND ?";
+            JOIN customer cu ON o.customer_id = cu.id
+            WHERE o.order_date BETWEEN ? AND ?
+            $employee_condition";
     
     $stmt = $conn->prepare($sql);
     $stmt->bind_param("ss", $start_date, $end_date);
@@ -383,13 +486,38 @@ function getRegionTotalSales($conn, $start_date, $end_date) {
  * @param mysqli $conn 数据库连接
  * @param string $start_date 开始日期
  * @param string $end_date 结束日期
+ * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  * @return array 活跃国家信息
  */
-function getActiveCountries($conn, $start_date, $end_date) {
+function getActiveCountries($conn, $start_date, $end_date, $employee_filter = null) {
+    // 如果有业务员过滤条件
+    $employee_condition = "";
+    
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter) && !empty($employee_filter)) {
+            // 处理数组形式的业务员ID列表
+            $emp_ids = [];
+            foreach ($employee_filter as $emp_id) {
+                if (is_numeric($emp_id)) {
+                    $emp_ids[] = intval($emp_id);
+                }
+            }
+            if (!empty($emp_ids)) {
+                $emp_ids_str = implode(',', $emp_ids);
+                $employee_condition = " AND cu.cs_belong IN ($emp_ids_str)";
+            }
+        } else if (is_numeric($employee_filter) && $employee_filter > 0) {
+            // 处理单个业务员ID
+            $employee_filter = intval($employee_filter);
+            $employee_condition = " AND cu.cs_belong = $employee_filter";
+        }
+    }
+    
     $sql = "SELECT COUNT(DISTINCT cu.cs_country) as country_count
             FROM orders o
             JOIN customer cu ON o.customer_id = cu.id
-            WHERE o.order_date BETWEEN ? AND ?";
+            WHERE o.order_date BETWEEN ? AND ?
+            $employee_condition";
     
     $stmt = $conn->prepare($sql);
     $stmt->bind_param("ss", $start_date, $end_date);
@@ -408,9 +536,33 @@ function getActiveCountries($conn, $start_date, $end_date) {
  * @param mysqli $conn 数据库连接
  * @param string $start_date 开始日期
  * @param string $end_date 结束日期
+ * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  * @return array 各地区平均订单金额数据
  */
-function getAverageOrderByRegion($conn, $start_date, $end_date) {
+function getAverageOrderByRegion($conn, $start_date, $end_date, $employee_filter = null) {
+    // 如果有业务员过滤条件
+    $employee_condition = "";
+    
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter) && !empty($employee_filter)) {
+            // 处理数组形式的业务员ID列表
+            $emp_ids = [];
+            foreach ($employee_filter as $emp_id) {
+                if (is_numeric($emp_id)) {
+                    $emp_ids[] = intval($emp_id);
+                }
+            }
+            if (!empty($emp_ids)) {
+                $emp_ids_str = implode(',', $emp_ids);
+                $employee_condition = " AND cu.cs_belong IN ($emp_ids_str)";
+            }
+        } else if (is_numeric($employee_filter) && $employee_filter > 0) {
+            // 处理单个业务员ID
+            $employee_filter = intval($employee_filter);
+            $employee_condition = " AND cu.cs_belong = $employee_filter";
+        }
+    }
+    
     $sql = "SELECT 
                 c.countryName, 
                 AVG(o.total_amount) as avg_amount,
@@ -419,6 +571,7 @@ function getAverageOrderByRegion($conn, $start_date, $end_date) {
             JOIN customer cu ON o.customer_id = cu.id
             JOIN country c ON cu.cs_country = c.id
             WHERE o.order_date BETWEEN ? AND ?
+            $employee_condition
             GROUP BY cu.cs_country
             HAVING order_count >= 5
             ORDER BY avg_amount DESC
@@ -459,9 +612,33 @@ function getAverageOrderByRegion($conn, $start_date, $end_date) {
  * @param mysqli $conn 数据库连接
  * @param string $start_date 开始日期
  * @param string $end_date 结束日期
+ * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  * @return array 各地区产品类别偏好数据
  */
-function getRegionCategoryPreferences($conn, $start_date, $end_date) {
+function getRegionCategoryPreferences($conn, $start_date, $end_date, $employee_filter = null) {
+    // 如果有业务员过滤条件
+    $employee_condition = "";
+    
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter) && !empty($employee_filter)) {
+            // 处理数组形式的业务员ID列表
+            $emp_ids = [];
+            foreach ($employee_filter as $emp_id) {
+                if (is_numeric($emp_id)) {
+                    $emp_ids[] = intval($emp_id);
+                }
+            }
+            if (!empty($emp_ids)) {
+                $emp_ids_str = implode(',', $emp_ids);
+                $employee_condition = " AND cu.cs_belong IN ($emp_ids_str)";
+            }
+        } else if (is_numeric($employee_filter) && $employee_filter > 0) {
+            // 处理单个业务员ID
+            $employee_filter = intval($employee_filter);
+            $employee_condition = " AND cu.cs_belong = $employee_filter";
+        }
+    }
+    
     $sql = "SELECT 
                 c.countryName, 
                 pc.name as category_name,
@@ -473,6 +650,7 @@ function getRegionCategoryPreferences($conn, $start_date, $end_date) {
             JOIN products p ON oi.product_id = p.id
             JOIN product_categories pc ON p.category_id = pc.id
             WHERE o.order_date BETWEEN ? AND ?
+            $employee_condition
             GROUP BY cu.cs_country, p.category_id
             ORDER BY c.countryName, total_quantity DESC";
     
@@ -523,11 +701,35 @@ function getRegionCategoryPreferences($conn, $start_date, $end_date) {
  * @param string $start_date 开始日期
  * @param string $end_date 结束日期
  * @param string $period 时间粒度 (day/week/month)
+ * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  * @return array 地区销售增长趋势数据
  */
-function getRegionGrowthTrends($conn, $start_date, $end_date, $period = 'month') {
+function getRegionGrowthTrends($conn, $start_date, $end_date, $period = 'month', $employee_filter = null) {
     $period_format = getPeriodFormat($period);
     
+    // 如果有业务员过滤条件
+    $employee_condition = "";
+    
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter) && !empty($employee_filter)) {
+            // 处理数组形式的业务员ID列表
+            $emp_ids = [];
+            foreach ($employee_filter as $emp_id) {
+                if (is_numeric($emp_id)) {
+                    $emp_ids[] = intval($emp_id);
+                }
+            }
+            if (!empty($emp_ids)) {
+                $emp_ids_str = implode(',', $emp_ids);
+                $employee_condition = " AND cu.cs_belong IN ($emp_ids_str)";
+            }
+        } else if (is_numeric($employee_filter) && $employee_filter > 0) {
+            // 处理单个业务员ID
+            $employee_filter = intval($employee_filter);
+            $employee_condition = " AND cu.cs_belong = $employee_filter";
+        }
+    }
+    
     $sql = "SELECT 
                 c.countryName,
                 DATE_FORMAT(o.order_date, ?) as time_period,
@@ -536,6 +738,7 @@ function getRegionGrowthTrends($conn, $start_date, $end_date, $period = 'month')
             JOIN customer cu ON o.customer_id = cu.id
             JOIN country c ON cu.cs_country = c.id
             WHERE o.order_date BETWEEN ? AND ?
+            $employee_condition
             GROUP BY cu.cs_country, time_period
             ORDER BY c.countryName, time_period";
     
@@ -577,9 +780,33 @@ function getRegionGrowthTrends($conn, $start_date, $end_date, $period = 'month')
  * 获取地区季节性销售分析
  * 
  * @param mysqli $conn 数据库连接
+ * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  * @return array 地区季节性销售分析数据
  */
-function getRegionSeasonalAnalysis($conn) {
+function getRegionSeasonalAnalysis($conn, $employee_filter = null) {
+    // 如果有业务员过滤条件
+    $employee_condition = "";
+    
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter) && !empty($employee_filter)) {
+            // 处理数组形式的业务员ID列表
+            $emp_ids = [];
+            foreach ($employee_filter as $emp_id) {
+                if (is_numeric($emp_id)) {
+                    $emp_ids[] = intval($emp_id);
+                }
+            }
+            if (!empty($emp_ids)) {
+                $emp_ids_str = implode(',', $emp_ids);
+                $employee_condition = " AND cu.cs_belong IN ($emp_ids_str)";
+            }
+        } else if (is_numeric($employee_filter) && $employee_filter > 0) {
+            // 处理单个业务员ID
+            $employee_filter = intval($employee_filter);
+            $employee_condition = " AND cu.cs_belong = $employee_filter";
+        }
+    }
+    
     $sql = "SELECT 
                 c.countryName,
                 MONTH(o.order_date) as month,
@@ -588,6 +815,7 @@ function getRegionSeasonalAnalysis($conn) {
             JOIN customer cu ON o.customer_id = cu.id
             JOIN country c ON cu.cs_country = c.id
             WHERE o.order_date >= DATE_SUB(CURDATE(), INTERVAL 2 YEAR)
+            $employee_condition
             GROUP BY cu.cs_country, month
             ORDER BY c.countryName, month";
     
@@ -624,9 +852,33 @@ function getRegionSeasonalAnalysis($conn) {
  * @param mysqli $conn 数据库连接
  * @param string $start_date 开始日期
  * @param string $end_date 结束日期
+ * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  * @return array 地区销售预测数据
  */
-function getRegionSalesForecast($conn, $start_date, $end_date) {
+function getRegionSalesForecast($conn, $start_date, $end_date, $employee_filter = null) {
+    // 如果有业务员过滤条件
+    $employee_condition = "";
+    
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter) && !empty($employee_filter)) {
+            // 处理数组形式的业务员ID列表
+            $emp_ids = [];
+            foreach ($employee_filter as $emp_id) {
+                if (is_numeric($emp_id)) {
+                    $emp_ids[] = intval($emp_id);
+                }
+            }
+            if (!empty($emp_ids)) {
+                $emp_ids_str = implode(',', $emp_ids);
+                $employee_condition = " AND cu.cs_belong IN ($emp_ids_str)";
+            }
+        } else if (is_numeric($employee_filter) && $employee_filter > 0) {
+            // 处理单个业务员ID
+            $employee_filter = intval($employee_filter);
+            $employee_condition = " AND cu.cs_belong = $employee_filter";
+        }
+    }
+    
     // 获取过去12个月的销售数据作为基础
     $sql = "SELECT 
                 c.countryName,
@@ -637,6 +889,7 @@ function getRegionSalesForecast($conn, $start_date, $end_date) {
             JOIN customer cu ON o.customer_id = cu.id
             JOIN country c ON cu.cs_country = c.id
             WHERE o.order_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
+            $employee_condition
             GROUP BY cu.cs_country, year, month
             ORDER BY c.countryName, year, month";
     

+ 150 - 98
statistics_utils.php

@@ -156,9 +156,14 @@ function getPeriodFormat($period) {
  * @param mysqli $conn 数据库连接
  * @param string $start_date 开始日期
  * @param string $end_date 结束日期
+ * @param array|int $employee_filter 业务员ID或ID数组,用于过滤数据 (可选)
  * @return array 新增客户详细数据
  */
-function getNewCustomersDetails($conn, $start_date, $end_date) {
+function getNewCustomersDetails($conn, $start_date, $end_date, $employee_filter = null) {
+    // 使用 mysqli_real_escape_string 防止 SQL 注入
+    $start_date = $conn->real_escape_string($start_date);
+    $end_date = $conn->real_escape_string($end_date);
+    
     $sql = "SELECT 
                 c.id,
                 c.cs_company as company_name,
@@ -171,19 +176,38 @@ function getNewCustomersDetails($conn, $start_date, $end_date) {
             LEFT JOIN country co ON c.cs_country = co.id
             LEFT JOIN clienttype ct ON c.cs_type = ct.id
             LEFT JOIN employee e ON c.cs_belong = e.id
-            WHERE c.cs_addtime BETWEEN ? AND ?
-            ORDER BY c.cs_addtime DESC
-            LIMIT 30";
-            
-    $stmt = $conn->prepare($sql);
-    $stmt->bind_param("ss", $start_date, $end_date);
-    $stmt->execute();
+            WHERE c.cs_addtime BETWEEN '$start_date' AND '$end_date'";
+    
+    // 如果有业务员过滤条件
+    if ($employee_filter !== null) {
+        if (is_array($employee_filter) && !empty($employee_filter)) {
+            // 处理数组形式的业务员ID列表
+            $emp_ids = array();
+            foreach ($employee_filter as $emp_id) {
+                if (is_numeric($emp_id)) {
+                    $emp_ids[] = intval($emp_id);
+                }
+            }
+            if (!empty($emp_ids)) {
+                $emp_ids_str = implode(',', $emp_ids);
+                $sql .= " AND c.cs_belong IN ($emp_ids_str)";
+            }
+        } else if (is_numeric($employee_filter) && $employee_filter > 0) {
+            // 处理单个业务员ID
+            $employee_filter = intval($employee_filter);
+            $sql .= " AND c.cs_belong = $employee_filter";
+        }
+    }
     
-    $result = $stmt->get_result();
+    $sql .= " ORDER BY c.cs_addtime DESC LIMIT 30";
+    
+    $result = $conn->query($sql);
     $customers = [];
     
-    while ($row = $result->fetch_assoc()) {
-        $customers[] = $row;
+    if ($result) {
+        while ($row = $result->fetch_assoc()) {
+            $customers[] = $row;
+        }
     }
     
     return $customers;
@@ -195,28 +219,45 @@ function getNewCustomersDetails($conn, $start_date, $end_date) {
  * @param mysqli $conn 数据库连接
  * @param string $start_date 开始日期
  * @param string $end_date 结束日期
+ * @param array $visible_employees 可见的业务员ID列表 (可选)
  * @return array 业务员新增客户统计数据
  */
-function getNewCustomersByEmployee($conn, $start_date, $end_date) {
+function getNewCustomersByEmployee($conn, $start_date, $end_date, $visible_employees = null) {
+    // 使用 mysqli_real_escape_string 防止 SQL 注入
+    $start_date = $conn->real_escape_string($start_date);
+    $end_date = $conn->real_escape_string($end_date);
+    
     $sql = "SELECT 
                 e.id as employee_id,
                 e.em_user as employee_name,
                 COUNT(c.id) as customer_count
             FROM employee e
-            LEFT JOIN customer c ON e.id = c.cs_belong AND c.cs_addtime BETWEEN ? AND ?
-            WHERE e.em_role IS NOT NULL
-            GROUP BY e.id
-            ORDER BY customer_count DESC";
-            
-    $stmt = $conn->prepare($sql);
-    $stmt->bind_param("ss", $start_date, $end_date);
-    $stmt->execute();
+            LEFT JOIN customer c ON e.id = c.cs_belong AND c.cs_addtime BETWEEN '$start_date' AND '$end_date'
+            WHERE e.em_role IS NOT NULL";
+    
+    // 如果指定了可见业务员列表,则添加过滤条件
+    if ($visible_employees !== null && !empty($visible_employees)) {
+        $emp_ids = array();
+        foreach ($visible_employees as $emp_id) {
+            if (is_numeric($emp_id)) {
+                $emp_ids[] = intval($emp_id);
+            }
+        }
+        if (!empty($emp_ids)) {
+            $emp_ids_str = implode(',', $emp_ids);
+            $sql .= " AND e.id IN ($emp_ids_str)";
+        }
+    }
     
-    $result = $stmt->get_result();
+    $sql .= " GROUP BY e.id ORDER BY customer_count DESC";
+    
+    $result = $conn->query($sql);
     $data = [];
     
-    while ($row = $result->fetch_assoc()) {
-        $data[] = $row;
+    if ($result) {
+        while ($row = $result->fetch_assoc()) {
+            $data[] = $row;
+        }
     }
     
     return $data;
@@ -431,90 +472,101 @@ function renderNewCustomersByEmployeeChart($employee_data) {
 }
 
 /**
- * 获取新客户购买产品明细
+ * 根据用户角色获取可见的业务员列表
  * 
  * @param mysqli $conn 数据库连接
- * @param string $start_date 开始日期
- * @param string $end_date 结束日期
- * @param int $category_id 产品分类ID,0表示所有分类
- * @return array 新客户购买产品数据
+ * @param int $user_id 当前用户ID
+ * @return array 可访问的业务员ID和姓名列表
  */
-function getNewCustomerProductPurchases($conn, $start_date, $end_date, $category_id = 0) {
-    // 获取在指定日期范围内首次购买的客户
-    $new_customer_sql = "
-        SELECT DISTINCT o.customer_id
-        FROM orders o
-        WHERE o.order_date BETWEEN ? AND ?
-        AND o.order_status != 0
-        AND NOT EXISTS (
-            SELECT 1 FROM orders o2 
-            WHERE o2.customer_id = o.customer_id 
-            AND o2.order_date < ?
-            AND o2.order_status != 0
-        )
-    ";
-    
-    $stmt = $conn->prepare($new_customer_sql);
-    $stmt->bind_param("sss", $start_date, $end_date, $start_date);
+function getAccessibleEmployees($conn, $user_id) {
+    // 获取当前用户信息
+    $sql = "SELECT em_user, em_role FROM employee WHERE id = ?";
+    $stmt = $conn->prepare($sql);
+    $stmt->bind_param("i", $user_id);
     $stmt->execute();
-    $new_customers_result = $stmt->get_result();
-    
-    $new_customer_ids = [];
-    while ($row = $new_customers_result->fetch_assoc()) {
-        $new_customer_ids[] = $row['customer_id'];
-    }
-    
-    // 如果没有新客户,返回空数组
-    if (empty($new_customer_ids)) {
-        return [];
-    }
-    
-    // 构建查询条件中的客户ID列表
-    $customer_ids_str = implode(',', $new_customer_ids);
-    
-    // 查询这些新客户购买的产品
-    $category_filter = "";
-    if ($category_id > 0) {
-        $category_filter = "AND p.category_id = " . intval($category_id);
+    $result = $stmt->get_result();
+    $user = $result->fetch_assoc();
+    $role = $user['em_role'] ?? 0;
+    
+    $employees = [];
+    
+    if ($role == 1) {
+        // 管理员可以看到所有业务员
+        $sql = "SELECT id, em_user FROM employee WHERE em_role IS NOT NULL ORDER BY em_user";
+        $result = $conn->query($sql);
+        while ($row = $result->fetch_assoc()) {
+            $employees[] = [
+                'id' => $row['id'],
+                'name' => $row['em_user']
+            ];
+        }
+    } else if ($role == 2) {
+        // 获取组长自己和其团队成员
+        $sql = "SELECT id, em_user FROM employee WHERE id = ? OR em_role = ? ORDER BY em_user";
+        $stmt = $conn->prepare($sql);
+        $stmt->bind_param("ii", $user_id, $user_id);
+        $stmt->execute();
+        $result = $stmt->get_result();
+        while ($row = $result->fetch_assoc()) {
+            $employees[] = [
+                'id' => $row['id'],
+                'name' => $row['em_user']
+            ];
+        }
+    } else {
+        // 普通业务员只能看到自己
+        $sql = "SELECT id, em_user FROM employee WHERE id = ?";
+        $stmt = $conn->prepare($sql);
+        $stmt->bind_param("i", $user_id);
+        $stmt->execute();
+        $result = $stmt->get_result();
+        while ($row = $result->fetch_assoc()) {
+            $employees[] = [
+                'id' => $row['id'],
+                'name' => $row['em_user']
+            ];
+        }
     }
     
-    $product_sql = "
-        SELECT 
-            p.id,
-            p.ProductName as product_name,
-            pc.name as category_name,
-            COUNT(DISTINCT o.id) as order_count,
-            COUNT(DISTINCT o.customer_id) as customer_count,
-            SUM(oi.quantity) as total_quantity,
-            SUM(oi.total_price) as total_revenue,
-            AVG(oi.unit_price) as avg_price
-        FROM orders o
-        JOIN order_items oi ON o.id = oi.order_id
-        JOIN products p ON oi.product_id = p.id
-        LEFT JOIN product_categories pc ON p.category_id = pc.id
-        WHERE o.customer_id IN ({$customer_ids_str})
-        AND o.order_date BETWEEN ? AND ?
-        AND o.order_status != 0
-        {$category_filter}
-        GROUP BY p.id
-        ORDER BY total_revenue DESC
-    ";
-    
-    $stmt = $conn->prepare($product_sql);
-    $stmt->bind_param("ss", $start_date, $end_date);
+    return $employees;
+}
+
+/**
+ * 根据用户角色获取默认的业务员筛选列表
+ * 
+ * @param mysqli $conn 数据库连接
+ * @param int $user_id 当前用户ID
+ * @return array|int|null 业务员筛选值,可能是单个ID、ID数组或null
+ */
+function getDefaultEmployeeFilter($conn, $user_id) {
+    // 获取当前用户角色
+    $sql = "SELECT em_role FROM employee WHERE id = ?";
+    $stmt = $conn->prepare($sql);
+    $stmt->bind_param("i", $user_id);
     $stmt->execute();
-    
     $result = $stmt->get_result();
-    $products = [];
-    
-    while ($row = $result->fetch_assoc()) {
-        $products[] = $row;
+    $user = $result->fetch_assoc();
+    $role = $user['em_role'] ?? 0;
+    
+    if ($role == 1) {
+        // 管理员默认看所有人
+        return null;
+    } else if ($role == 2) {
+        // 团队组长默认看他的团队
+        $sql = "SELECT id FROM employee WHERE id = ? OR em_role = ?";
+        $stmt = $conn->prepare($sql);
+        $stmt->bind_param("ii", $user_id, $user_id);
+        $stmt->execute();
+        $result = $stmt->get_result();
+        $emp_ids = [];
+        while ($row = $result->fetch_assoc()) {
+            $emp_ids[] = $row['id'];
+        }
+        return $emp_ids;
+    } else {
+        // 普通业务员只看自己
+        return $user_id;
     }
-    
-    return [
-        'new_customer_count' => count($new_customer_ids),
-        'products' => $products
-    ];
 }
 
 /**

+ 199 - 183
subCustomers.php

@@ -2,29 +2,84 @@
 require_once 'conn.php';
 checkLogin();
 
+// 检查当前用户是否为组长
+$isLeader = false;
+$userInfoQuery = "SELECT em_role, em_permission_role_id FROM employee WHERE id = " . $_SESSION['employee_id'];
+$userResult = $conn->query($userInfoQuery);
+if ($userResult && $userRow = $userResult->fetch_assoc()) {
+    // 只有 em_permission_role_id=2 表示该用户是组长
+    $isLeader = ($userRow['em_permission_role_id'] == 2);
+}
+
+// 如果不是组长,直接跳转到客户列表页面
+if (!$isLeader) {
+    header('Location: customers.php');
+    exit;
+}
+
 $act = $_GET['act'] ?? '';
 
 if ($act == 'postchk') {
     $keys = urlencode($_GET['Keys'] ?? '');
     $page = $_GET['Page'] ?? '';
-    $chkact = str_replace('t', '', $_POST['chkact'] ?? '');
+    $chkact = $_POST['chkact'] ?? '';
     
     if (isset($_POST['chkbox'])) {
         $sqlStr = "(" . implode(',', array_map('intval', (array)$_POST['chkbox'])) . ")";
+        $count = count($_POST['chkbox']);
         
-        if ($chkact == '0') {
-            $sql = "UPDATE customer SET cs_deal=" . (int)$chkact . " WHERE id IN " . $sqlStr;
-        } else {
+        // 检查是否为员工转让操作
+        if (substr($chkact, 0, 1) === 't') {
+            // 从chkact值中提取员工ID
+            $employeeId = (int)substr($chkact, 1);
+            
+            // 获取员工代码和名称
+            $stmt = $conn->prepare("SELECT em_code, em_user FROM employee WHERE id = ?");
+            $stmt->bind_param("i", $employeeId);
+            $stmt->execute();
+            $result = $stmt->get_result();
+            $employeeCode = '';
+            $employeeName = '未知业务员';
+            if ($row = $result->fetch_assoc()) {
+                $employeeCode = $row['em_code'];
+                $employeeName = $row['em_user'];
+            }
+            $stmt->close();
+            
+            // 更新客户记录
             $sql = "UPDATE customer SET 
-                    cs_code=REPLACE(cs_code, '-', '/0'+(SELECT SUBSTRING(em_code,2,2) FROM employee WHERE id=" . (int)$chkact . ")+'-'), 
-                    cs_belong=" . (int)$chkact . ", 
-                    cs_chain=CONCAT(cs_chain,'," . (int)$chkact . "') 
-                    WHERE id IN " . $sqlStr;
+                   cs_updatetime = NOW(),
+                   cs_code = REPLACE(cs_code, '-', '/{$employeeCode}-'),
+                   cs_belong = {$employeeId},
+                   cs_chain = CONCAT(cs_chain, ',{$employeeId}')
+                   WHERE id IN {$sqlStr}";
+            $conn->query($sql);
+            
+            // 记录操作日志
+            $ids = implode(',', array_map('intval', (array)$_POST['chkbox']));
+            $action = "{$_SESSION['employee_name']} 批量转移{$count}个客户({$ids})给组员【{$employeeName}】";
+            logAction($action);
+            
+        } else {
+            $chkact = (int)$chkact;
+            $sql = "UPDATE customer SET cs_deal = {$chkact} WHERE id IN {$sqlStr}";
+            $conn->query($sql);
+            
+            // 记录跟进阶段变更日志
+            $dealStatus = "";
+            switch($chkact) {
+                case 0: $dealStatus = "无响应"; break;
+                case 1: $dealStatus = "背景调查"; break;
+                case 2: $dealStatus = "明确需求"; break;
+                case 3: $dealStatus = "已成交"; break;
+                default: $dealStatus = "未知状态";
+            }
+            $ids = implode(',', array_map('intval', (array)$_POST['chkbox']));
+            $action = "{$_SESSION['employee_name']} 批量将{$count}个客户({$ids})的跟进阶段更改为【{$dealStatus}】";
+            logAction($action);
         }
         
         $deleteTag = "DELETE FROM tagtable WHERE customerId IN " . $sqlStr;
-        
-        $conn->query($sql);
         $conn->query($deleteTag);
     }
     
@@ -32,50 +87,56 @@ if ($act == 'postchk') {
     exit;
 }
 
+// 处理搜索和过滤参数
 $keys = $_GET['Keys'] ?? '';
+$keys = str_replace([" ", "+"], "", $keys);
 $keyscode = textEncode($keys);
 $page = $_GET['Page'] ?? '';
 
-$filterCountry = $_GET['fliterCountry'] ?? '';
-$filterQudao = $_GET['fliterQudao'] ?? '';
-$filterDeal = $_GET['fliterDeal'] ?? '';
-$filterBusiness = $_GET['fliterBusiness'] ?? '';
-$filterContact = $_GET['fliterContact'] ?? '';
+$filters = [
+    'Country' => $_GET['fliterCountry'] ?? '',
+    'Qudao' => $_GET['fliterQudao'] ?? '',
+    'Deal' => $_GET['fliterDeal'] ?? '',
+    'Business' => $_GET['fliterBusiness'] ?? '',
+    'Contact' => $_GET['fliterContact'] ?? ''
+];
 
 $filterStr = "";
 $urlStr = "";
 
-if (!empty($filterCountry)) {
-    $filterStr .= " AND c.cs_country=" . (int)$filterCountry;
-    $urlStr .= "&fliterCountry=" . $filterCountry;
+// 构建过滤条件
+if (!empty($filters['Country'])) {
+    $filterStr .= " AND c.cs_country=" . (int)$filters['Country'];
+    $urlStr .= "&fliterCountry=" . $filters['Country'];
 }
 
-if (!empty($filterQudao)) {
-    $filterStr .= " AND c.cs_from=" . (int)$filterQudao;
-    $urlStr .= "&fliterQudao=" . $filterQudao;
+if (!empty($filters['Qudao'])) {
+    $filterStr .= " AND c.cs_from=" . (int)$filters['Qudao'];
+    $urlStr .= "&fliterQudao=" . $filters['Qudao'];
 }
 
-if (!empty($filterDeal)) {
-    $filterStr .= " AND c.cs_deal=" . (int)$filterDeal;
-    $urlStr .= "&fliterDeal=" . $filterDeal;
+if (!empty($filters['Deal'])) {
+    $filterStr .= " AND c.cs_deal=" . (int)$filters['Deal'];
+    $urlStr .= "&fliterDeal=" . $filters['Deal'];
 }
 
-if (!empty($filterBusiness)) {
-    $filterStr .= " AND c.cs_type=" . (int)$filterBusiness;
-    $urlStr .= "&fliterBusiness=" . $filterBusiness;
+if (!empty($filters['Business'])) {
+    $filterStr .= " AND c.cs_type=" . (int)$filters['Business'];
+    $urlStr .= "&fliterBusiness=" . $filters['Business'];
 }
 
-if (!empty($filterContact)) {
-    switch ($filterContact) {
-        case "1": $filterStr .= " AND (cc.tel_1 != '' OR cc.tel_2 != '' OR cc.tel_3 != '')"; break;
-        case "2": $filterStr .= " AND (cc.wechat_1 != '' OR cc.wechat_2 != '' OR cc.wechat_3 != '')"; break;
-        case "3": $filterStr .= " AND (cc.whatsapp_1 != '' OR cc.whatsapp_2 != '' OR cc.whatsapp_3 != '')"; break;
-        case "4": $filterStr .= " AND (cc.email_1 != '' OR cc.email_2 != '' OR cc.email_3 != '')"; break;
-        case "5": $filterStr .= " AND (cc.linkedin_1 != '' OR cc.linkedin_2 != '' OR cc.linkedin_3 != '')"; break;
-        case "6": $filterStr .= " AND (cc.facebook_1 != '' OR cc.facebook_2 != '' OR cc.facebook_3 != '')"; break;
-        case "7": $filterStr .= " AND (cc.alibaba_1 != '' OR cc.alibaba_2 != '' OR cc.alibaba_3 != '')"; break;
+// 改进联系方式过滤查询
+if (!empty($filters['Contact'])) {
+    switch ($filters['Contact']) {
+        case "1": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE tel_1 != '' OR tel_2 != '' OR tel_3 != '')"; break;
+        case "2": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE wechat_1 != '' OR wechat_2 != '' OR wechat_3 != '')"; break;
+        case "3": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE whatsapp_1 != '' OR whatsapp_2 != '' OR whatsapp_3 != '')"; break;
+        case "4": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE email_1 != '' OR email_2 != '' OR email_3 != '')"; break;
+        case "5": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE linkedin_1 != '' OR linkedin_2 != '' OR linkedin_3 != '')"; break;
+        case "6": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE facebook_1 != '' OR facebook_2 != '' OR facebook_3 != '')"; break;
+        case "7": $filterStr .= " AND c.id IN (SELECT customer_id FROM customer_contact WHERE alibaba_1 != '' OR alibaba_2 != '' OR alibaba_3 != '')"; break;
     }
-    $urlStr .= "&fliterContact=" . $filterContact;
+    $urlStr .= "&fliterContact=" . $filters['Contact'];
 }
 
 $keys = urlencode($keys);
@@ -114,7 +175,7 @@ $hrefstr = "?keys=" . $keys;
                     <?php
                     $result = $conn->query("SELECT id, countryName FROM country ORDER BY CONVERT(countryName USING gbk) COLLATE gbk_chinese_ci ASC");
                     while ($row = $result->fetch_assoc()) {
-                        $selected = ($filterCountry == $row['id']) ? ' selected="selected"' : '';
+                        $selected = ($filters['Country'] == $row['id']) ? ' selected="selected"' : '';
                         echo "<option value=\"{$row['id']}\"{$selected}>{$row['countryName']}</option>";
                     }
                     ?>
@@ -127,7 +188,7 @@ $hrefstr = "?keys=" . $keys;
                     <?php
                     $result = $conn->query("SELECT id, ch_name FROM qudao");
                     while ($row = $result->fetch_assoc()) {
-                        $selected = ($filterQudao == $row['id']) ? ' selected="selected"' : '';
+                        $selected = ($filters['Qudao'] == $row['id']) ? ' selected="selected"' : '';
                         echo "<option value=\"{$row['id']}\"{$selected}>{$row['ch_name']}</option>";
                     }
                     ?>
@@ -137,10 +198,10 @@ $hrefstr = "?keys=" . $keys;
                 <label>跟进阶段</label>
                 <select name="fliterDeal" class="filterSearch">
                     <option value="">请选择</option>
-                    <option value="0"<?= ($filterDeal == "0") ? ' selected="selected"' : '' ?>>无响应</option>
-                    <option value="1"<?= ($filterDeal == "1") ? ' selected="selected"' : '' ?>>背景调查</option>
-                    <option value="2"<?= ($filterDeal == "2") ? ' selected="selected"' : '' ?>>明确需求</option>
-                    <option value="3"<?= ($filterDeal == "3") ? ' selected="selected"' : '' ?>>已成交</option>
+                    <option value="0"<?= ($filters['Deal'] == "0") ? ' selected="selected"' : '' ?>>无响应</option>
+                    <option value="1"<?= ($filters['Deal'] == "1") ? ' selected="selected"' : '' ?>>背景调查</option>
+                    <option value="2"<?= ($filters['Deal'] == "2") ? ' selected="selected"' : '' ?>>明确需求</option>
+                    <option value="3"<?= ($filters['Deal'] == "3") ? ' selected="selected"' : '' ?>>已成交</option>
                 </select>
             </div>
             <div class="selectItem">
@@ -150,7 +211,7 @@ $hrefstr = "?keys=" . $keys;
                     <?php
                     $result = $conn->query("SELECT id, businessType FROM clienttype");
                     while ($row = $result->fetch_assoc()) {
-                        $selected = ($filterBusiness == $row['id']) ? ' selected="selected"' : '';
+                        $selected = ($filters['Business'] == $row['id']) ? ' selected="selected"' : '';
                         echo "<option value=\"{$row['id']}\"{$selected}>{$row['businessType']}</option>";
                     }
                     ?>
@@ -160,18 +221,19 @@ $hrefstr = "?keys=" . $keys;
                 <label>联系方式</label>
                 <select name="fliterContact" class="filterSearch">
                     <option value="">请选择</option>
-                    <option value="1"<?= ($filterContact == "1") ? ' selected="selected"' : '' ?>>电话</option>
-                    <option value="2"<?= ($filterContact == "2") ? ' selected="selected"' : '' ?>>微信</option>
-                    <option value="3"<?= ($filterContact == "3") ? ' selected="selected"' : '' ?>>WhatsApp</option>
-                    <option value="4"<?= ($filterContact == "4") ? ' selected="selected"' : '' ?>>邮箱</option>
-                    <option value="5"<?= ($filterContact == "5") ? ' selected="selected"' : '' ?>>领英</option>
-                    <option value="6"<?= ($filterContact == "6") ? ' selected="selected"' : '' ?>>Facebook</option>
-                    <option value="7"<?= ($filterContact == "7") ? ' selected="selected"' : '' ?>>阿里巴巴</option>
+                    <option value="1"<?= ($filters['Contact'] == "1") ? ' selected="selected"' : '' ?>>电话</option>
+                    <option value="2"<?= ($filters['Contact'] == "2") ? ' selected="selected"' : '' ?>>微信</option>
+                    <option value="3"<?= ($filters['Contact'] == "3") ? ' selected="selected"' : '' ?>>WhatsApp</option>
+                    <option value="4"<?= ($filters['Contact'] == "4") ? ' selected="selected"' : '' ?>>邮箱</option>
+                    <option value="5"<?= ($filters['Contact'] == "5") ? ' selected="selected"' : '' ?>>领英</option>
+                    <option value="6"<?= ($filters['Contact'] == "6") ? ' selected="selected"' : '' ?>>Facebook</option>
+                    <option value="7"<?= ($filters['Contact'] == "7") ? ' selected="selected"' : '' ?>>阿里巴巴</option>
                 </select>
             </div>
             <div class="inputSearch">
                 <input type="text" id="keys" class="inputTxt" placeholder="请输入搜索关键词"
-                       value="<?= empty($keyscode) ? '' : htmlspecialcharsFix($keyscode) ?>"/>
+                       value="<?= empty($keyscode) ? '' : htmlspecialcharsFix($keyscode) ?>"
+                       onKeyDown="if(event.keyCode==13){location.href='?Keys='+encodeURIComponent(document.getElementById('keys').value)}" />
                 <input type="button" id="searchgo" class="searchgo" value="go" 
                        onClick="location.href='?Keys='+encodeURIComponent(document.getElementById('keys').value)" />
             </div>
@@ -191,69 +253,62 @@ $hrefstr = "?keys=" . $keys;
             </div>
 
 <?php
-$sqlStr = "SELECT c.id, c.cs_code, c.cs_from, c.cs_country, c.cs_type, c.cs_deal, c.cs_addtime, c.cs_belong, 
-           c.cs_note, c.cs_claimFrom, 
-           cc.id as contact_id, cc.contact_name,
-           cc.tel_1, cc.tel_1_format, cc.tel_1_bu,
-           cc.tel_2, cc.tel_2_format, cc.tel_2_bu,
-           cc.tel_3, cc.tel_3_format, cc.tel_3_bu,
-           cc.email_1, cc.email_1_bu,
-           cc.email_2, cc.email_2_bu,
-           cc.email_3, cc.email_3_bu,
-           cc.whatsapp_1, cc.whatsapp_1_format, cc.whatsapp_1_bu,
-           cc.whatsapp_2, cc.whatsapp_2_format, cc.whatsapp_2_bu,
-           cc.whatsapp_3, cc.whatsapp_3_format, cc.whatsapp_3_bu,
-           cc.wechat_1, cc.wechat_1_bu,
-           cc.wechat_2, cc.wechat_2_bu,
-           cc.wechat_3, cc.wechat_3_bu,
-           cc.linkedin_1, cc.linkedin_1_bu,
-           cc.linkedin_2, cc.linkedin_2_bu,
-           cc.linkedin_3, cc.linkedin_3_bu,
-           cc.facebook_1, cc.facebook_1_bu,
-           cc.facebook_2, cc.facebook_2_bu,
-           cc.facebook_3, cc.facebook_3_bu,
-           cc.alibaba_1, cc.alibaba_1_bu,
-           cc.alibaba_2, cc.alibaba_2_bu,
-           cc.alibaba_3, cc.alibaba_3_bu
-           FROM customer c 
-           LEFT JOIN customer_contact cc ON c.id = cc.customer_id
-           WHERE (c.cs_code LIKE '%" . $conn->real_escape_string($keyscode) . "%' 
-           OR cc.contact_name LIKE '%" . $conn->real_escape_string($keyscode) . "%' 
-           OR cc.tel_1 LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.tel_2 LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.tel_3 LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.email_1 LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.email_2 LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.email_3 LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.wechat_1 LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.wechat_2 LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.wechat_3 LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.whatsapp_1_format LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.whatsapp_2_format LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.whatsapp_3_format LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.linkedin_1 LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.linkedin_2 LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.linkedin_3 LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.facebook_1 LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.facebook_2 LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.facebook_3 LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.alibaba_1 LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.alibaba_2 LIKE '%" . $conn->real_escape_string($keyscode) . "%'
-           OR cc.alibaba_3 LIKE '%" . $conn->real_escape_string($keyscode) . "%') 
-           AND c.cs_belong IN (SELECT id FROM employee WHERE em_role=" . $_SESSION['employee_id'] . ")" . 
-           $filterStr . " ORDER BY c.cs_state DESC, c.id DESC";
+// 优化SQL查询
+$sql = "SELECT c.id, c.cs_code, c.cs_from, c.cs_country, c.cs_type, c.cs_deal, c.cs_addtime, c.cs_belong, 
+        c.cs_note, c.cs_claimFrom 
+        FROM customer c 
+        WHERE c.cs_belong IN (SELECT id FROM employee WHERE em_role=" . $_SESSION['employee_id'] . ")";
+
+// 构建搜索条件
+$searchPattern = mysqli_real_escape_string($conn, $keyscode);
+if(!empty($searchPattern)) {
+    $sql .= " AND (c.cs_code LIKE '%$searchPattern%' 
+            OR c.id IN (SELECT customer_id FROM customer_contact WHERE 
+                contact_name LIKE '%$searchPattern%' OR
+                tel_1 LIKE '%$searchPattern%' OR
+                tel_2 LIKE '%$searchPattern%' OR
+                tel_3 LIKE '%$searchPattern%' OR
+                email_1 LIKE '%$searchPattern%' OR
+                email_2 LIKE '%$searchPattern%' OR
+                email_3 LIKE '%$searchPattern%' OR
+                wechat_1 LIKE '%$searchPattern%' OR
+                wechat_2 LIKE '%$searchPattern%' OR
+                wechat_3 LIKE '%$searchPattern%' OR
+                whatsapp_1_format LIKE '%$searchPattern%' OR
+                whatsapp_2_format LIKE '%$searchPattern%' OR
+                whatsapp_3_format LIKE '%$searchPattern%' OR
+                linkedin_1 LIKE '%$searchPattern%' OR
+                linkedin_2 LIKE '%$searchPattern%' OR
+                linkedin_3 LIKE '%$searchPattern%' OR
+                facebook_1 LIKE '%$searchPattern%' OR
+                facebook_2 LIKE '%$searchPattern%' OR
+                facebook_3 LIKE '%$searchPattern%' OR
+                alibaba_1 LIKE '%$searchPattern%' OR
+                alibaba_2 LIKE '%$searchPattern%' OR
+                alibaba_3 LIKE '%$searchPattern%')
+            OR c.id IN (SELECT customerId FROM tagtable WHERE tagName LIKE '%$searchPattern%'))";
+}
+
+// 添加过滤条件
+$sql .= $filterStr . " ORDER BY c.cs_state DESC, c.id DESC";
 
-$result = $conn->query($sqlStr);
+// 执行查询
+$result = $conn->query($sql);
 
 if ($result && $result->num_rows > 0) {
+    // 优化分页逻辑
     $pageSize = 15;
+    $totalRecords = $result->num_rows;
+    $totalPages = ceil($totalRecords / $pageSize);
+    
     $page = empty($page) ? 1 : $page;
-    $page = ($page === 'end') ? ceil($result->num_rows / $pageSize) : $page;
+    $page = ($page === 'end') ? $totalPages : $page;
     $page = (!is_numeric($page) || $page < 1) ? 1 : (int)$page;
-    $totalPages = ceil($result->num_rows / $pageSize);
     $page = ($page > $totalPages) ? $totalPages : $page;
+    
     $offset = $pageSize * ($page - 1);
     
+    // 获取记录
     $rows = [];
     while ($row = $result->fetch_assoc()) {
         $rows[] = $row;
@@ -264,6 +319,11 @@ if ($result && $result->num_rows > 0) {
     
     foreach ($paginatedRows as $row) {
         $tempNum++;
+        
+        // 获取联系人信息
+        $contactSql = "SELECT * FROM customer_contact WHERE customer_id = " . $row['id'];
+        $contactResult = $conn->query($contactSql);
+        $contactData = $contactResult->num_rows > 0 ? $contactResult->fetch_assoc() : null;
 ?>
         <div class="tline">
             <div class="col1" align="center"><input type="checkbox" name="chkbox[]" value="<?= $row['id'] ?>" /></div>
@@ -316,83 +376,39 @@ if ($result && $result->num_rows > 0) {
         <div class="notepanel clear">
             <div class="noteItem">联系方式</div>
             <div class="lx">
-                <div class="tel">
-                    <?php if(!empty($row['tel_1'])): ?>
-                        <div><?= htmlspecialcharsFix($row['tel_1']) ?></div>
-                    <?php endif; ?>
-                    <?php if(!empty($row['tel_2'])): ?>
-                        <div><?= htmlspecialcharsFix($row['tel_2']) ?></div>
-                    <?php endif; ?>
-                    <?php if(!empty($row['tel_3'])): ?>
-                        <div><?= htmlspecialcharsFix($row['tel_3']) ?></div>
-                    <?php endif; ?>
-                </div>
-                <div class="mail">
-                    <?php if(!empty($row['email_1'])): ?>
-                        <div><a href="mailto:<?= htmlspecialcharsFix($row['email_1']) ?>"><?= htmlspecialcharsFix($row['email_1']) ?></a></div>
-                    <?php endif; ?>
-                    <?php if(!empty($row['email_2'])): ?>
-                        <div><a href="mailto:<?= htmlspecialcharsFix($row['email_2']) ?>"><?= htmlspecialcharsFix($row['email_2']) ?></a></div>
-                    <?php endif; ?>
-                    <?php if(!empty($row['email_3'])): ?>
-                        <div><a href="mailto:<?= htmlspecialcharsFix($row['email_3']) ?>"><?= htmlspecialcharsFix($row['email_3']) ?></a></div>
-                    <?php endif; ?>
-                </div>
-                <div class="whatsapp">
-                    <?php if(!empty($row['whatsapp_1'])): ?>
-                        <div><?= htmlspecialcharsFix($row['whatsapp_1']) ?></div>
-                    <?php endif; ?>
-                    <?php if(!empty($row['whatsapp_2'])): ?>
-                        <div><?= htmlspecialcharsFix($row['whatsapp_2']) ?></div>
-                    <?php endif; ?>
-                    <?php if(!empty($row['whatsapp_3'])): ?>
-                        <div><?= htmlspecialcharsFix($row['whatsapp_3']) ?></div>
-                    <?php endif; ?>
-                </div>
-                <div class="wechat">
-                    <?php if(!empty($row['wechat_1'])): ?>
-                        <div><?= htmlspecialcharsFix($row['wechat_1']) ?></div>
-                    <?php endif; ?>
-                    <?php if(!empty($row['wechat_2'])): ?>
-                        <div><?= htmlspecialcharsFix($row['wechat_2']) ?></div>
-                    <?php endif; ?>
-                    <?php if(!empty($row['wechat_3'])): ?>
-                        <div><?= htmlspecialcharsFix($row['wechat_3']) ?></div>
-                    <?php endif; ?>
-                </div>
-                <div class="linkedin">
-                    <?php if(!empty($row['linkedin_1'])): ?>
-                        <div><?= htmlspecialcharsFix($row['linkedin_1']) ?></div>
-                    <?php endif; ?>
-                    <?php if(!empty($row['linkedin_2'])): ?>
-                        <div><?= htmlspecialcharsFix($row['linkedin_2']) ?></div>
-                    <?php endif; ?>
-                    <?php if(!empty($row['linkedin_3'])): ?>
-                        <div><?= htmlspecialcharsFix($row['linkedin_3']) ?></div>
-                    <?php endif; ?>
-                </div>
-                <div class="facebook">
-                    <?php if(!empty($row['facebook_1'])): ?>
-                        <div><?= htmlspecialcharsFix($row['facebook_1']) ?></div>
-                    <?php endif; ?>
-                    <?php if(!empty($row['facebook_2'])): ?>
-                        <div><?= htmlspecialcharsFix($row['facebook_2']) ?></div>
-                    <?php endif; ?>
-                    <?php if(!empty($row['facebook_3'])): ?>
-                        <div><?= htmlspecialcharsFix($row['facebook_3']) ?></div>
-                    <?php endif; ?>
-                </div>
-                <div class="alibaba">
-                    <?php if(!empty($row['alibaba_1'])): ?>
-                        <div><?= htmlspecialcharsFix($row['alibaba_1']) ?></div>
-                    <?php endif; ?>
-                    <?php if(!empty($row['alibaba_2'])): ?>
-                        <div><?= htmlspecialcharsFix($row['alibaba_2']) ?></div>
-                    <?php endif; ?>
-                    <?php if(!empty($row['alibaba_3'])): ?>
-                        <div><?= htmlspecialcharsFix($row['alibaba_3']) ?></div>
-                    <?php endif; ?>
-                </div>
+            <?php 
+            // 展示联系人信息
+            if ($contactData) {
+                $contactFields = [
+                    'tel' => ['电话', false],
+                    'email' => ['邮箱', true],
+                    'whatsapp' => ['WhatsApp', false],
+                    'wechat' => ['微信', false],
+                    'linkedin' => ['领英', false],
+                    'facebook' => ['Facebook', false],
+                    'alibaba' => ['阿里巴巴', false]
+                ];
+                
+                foreach ($contactFields as $fieldBase => $config) {
+                    $fieldName = $config[0];
+                    $isEmail = $config[1];
+                    
+                    echo "<div class=\"$fieldBase\">";
+                    for ($i = 1; $i <= 3; $i++) {
+                        $field = $fieldBase . '_' . $i;
+                        if (!empty($contactData[$field])) {
+                            if ($isEmail) {
+                                echo "<div><a href=\"mailto:" . htmlspecialcharsFix($contactData[$field]) . "\">" . 
+                                     htmlspecialcharsFix($contactData[$field]) . "</a></div>";
+                            } else {
+                                echo "<div>" . htmlspecialcharsFix($contactData[$field]) . "</div>";
+                            }
+                        }
+                    }
+                    echo "</div>";
+                }
+            }
+            ?>
             </div>
             <div class="noteItem2">备注</div>
             <div class="notecontent"><?= htmlUnCode($row['cs_note']) ?></div>

+ 82 - 105
subTag.php

@@ -2,12 +2,40 @@
 require_once 'conn.php';
 checkLogin();
 
+// 检查当前用户是否为组长
+$isLeader = false;
+$userInfoQuery = "SELECT em_role, em_permission_role_id FROM employee WHERE id = " . $_SESSION['employee_id'];
+$userResult = $conn->query($userInfoQuery);
+if ($userResult && $userRow = $userResult->fetch_assoc()) {
+    // 只有 em_permission_role_id=2 表示该用户是组长
+    $isLeader = ($userRow['em_permission_role_id'] == 2);
+}
+
+// 如果不是组长,直接跳转到客户列表页面
+if (!$isLeader) {
+    header('Location: customers.php');
+    exit;
+}
+
 // 获取URL参数
 $tagName = $_GET['tagName'] ?? '';
-$employeeId = $_GET['employeeId'] ?? 0;
+$employeeId = $_GET['employeeId'] ?? $_SESSION['employee_id'];
 
 if (empty($employeeId) || !is_numeric($employeeId)) {
-    $employeeId = 0;
+    $employeeId = $_SESSION['employee_id'];
+}
+
+// 如果不是组长,只能查看自己的数据
+if (!$isLeader) {
+    $employeeId = $_SESSION['employee_id'];
+} else if ($employeeId != $_SESSION['employee_id']) {
+    // 如果是组长查看组员数据,确认该员工确实是自己的组员
+    $checkSubordinate = "SELECT id FROM employee WHERE id = $employeeId AND em_role = " . $_SESSION['employee_id'];
+    $checkResult = $conn->query($checkSubordinate);
+    if (!$checkResult || $checkResult->num_rows == 0) {
+        // 不是自己的组员,只能查看自己的数据
+        $employeeId = $_SESSION['employee_id'];
+    }
 }
 
 if (empty($tagName)) {
@@ -40,6 +68,17 @@ if (empty($tagName)) {
 <div id="man_zone">
     <div class="fastSelect clear">
         <h1>标签:<?= htmlspecialcharsFix($tagName) ?></h1>
+        <?php if ($isLeader): ?>
+        <p>查看员工: <?php 
+            $empQuery = "SELECT em_user FROM employee WHERE id = $employeeId";
+            $empResult = $conn->query($empQuery);
+            if ($empResult && $empRow = $empResult->fetch_assoc()) {
+                echo htmlspecialcharsFix($empRow['em_user']);
+            } else {
+                echo "未知";
+            }
+        ?></p>
+        <?php endif; ?>
     </div>
 
     <div width="100%" border="0" cellpadding="3" cellspacing="1" class="table2">
@@ -55,33 +94,10 @@ if (empty($tagName)) {
         </div>
 
         <?php
-        // 组合查询SQL,使用LEFT JOIN获取联系人信息
-        $sqlStr = "SELECT c.id, c.cs_code, c.cs_from, c.cs_country, c.cs_type, c.cs_deal, c.cs_addtime, c.cs_note,
-                  cc.id as contact_id, cc.contact_name,
-                  cc.tel_1, cc.tel_1_format, cc.tel_1_bu,
-                  cc.tel_2, cc.tel_2_format, cc.tel_2_bu,
-                  cc.tel_3, cc.tel_3_format, cc.tel_3_bu,
-                  cc.email_1, cc.email_1_bu,
-                  cc.email_2, cc.email_2_bu,
-                  cc.email_3, cc.email_3_bu,
-                  cc.whatsapp_1, cc.whatsapp_1_format, cc.whatsapp_1_bu,
-                  cc.whatsapp_2, cc.whatsapp_2_format, cc.whatsapp_2_bu,
-                  cc.whatsapp_3, cc.whatsapp_3_format, cc.whatsapp_3_bu,
-                  cc.wechat_1, cc.wechat_1_bu,
-                  cc.wechat_2, cc.wechat_2_bu,
-                  cc.wechat_3, cc.wechat_3_bu,
-                  cc.linkedin_1, cc.linkedin_1_bu,
-                  cc.linkedin_2, cc.linkedin_2_bu,
-                  cc.linkedin_3, cc.linkedin_3_bu,
-                  cc.facebook_1, cc.facebook_1_bu,
-                  cc.facebook_2, cc.facebook_2_bu,
-                  cc.facebook_3, cc.facebook_3_bu,
-                  cc.alibaba_1, cc.alibaba_1_bu,
-                  cc.alibaba_2, cc.alibaba_2_bu,
-                  cc.alibaba_3, cc.alibaba_3_bu
+        // 优化SQL查询:如果是组长,可以根据所选组员查看,否则只看自己的
+        $sqlStr = "SELECT c.id, c.cs_code, c.cs_from, c.cs_country, c.cs_type, c.cs_deal, c.cs_addtime, c.cs_note, c.cs_belong
                   FROM customer c
-                  LEFT JOIN customer_contact cc ON c.id = cc.customer_id
-                  WHERE c.cs_belong=" . (int)$employeeId . " 
+                  WHERE c.cs_belong = $employeeId 
                   AND c.id IN (SELECT customerId FROM tagtable WHERE tagName='" . $conn->real_escape_string($tagName) . "')";
 
         $result = $conn->query($sqlStr);
@@ -90,6 +106,11 @@ if (empty($tagName)) {
         if ($result && $result->num_rows > 0) {
             while ($row = $result->fetch_assoc()) {
                 $tempNum++;
+                
+                // 获取联系人信息
+                $contactSql = "SELECT * FROM customer_contact WHERE customer_id = " . $row['id'];
+                $contactResult = $conn->query($contactSql);
+                $contactData = $contactResult->num_rows > 0 ? $contactResult->fetch_assoc() : null;
         ?>
                 <div class="tline">
                     <div class="col2"><?= $tempNum ?></div>
@@ -131,83 +152,39 @@ if (empty($tagName)) {
                 <div class="notepanel clear">
                     <div class="noteItem">联系方式</div>
                     <div class="lx">
-                        <div class="tel">
-                            <?php if(!empty($row['tel_1'])): ?>
-                                <div><?= htmlspecialcharsFix($row['tel_1']) ?></div>
-                            <?php endif; ?>
-                            <?php if(!empty($row['tel_2'])): ?>
-                                <div><?= htmlspecialcharsFix($row['tel_2']) ?></div>
-                            <?php endif; ?>
-                            <?php if(!empty($row['tel_3'])): ?>
-                                <div><?= htmlspecialcharsFix($row['tel_3']) ?></div>
-                            <?php endif; ?>
-                        </div>
-                        <div class="mail">
-                            <?php if(!empty($row['email_1'])): ?>
-                                <div><a href="mailto:<?= htmlspecialcharsFix($row['email_1']) ?>"><?= htmlspecialcharsFix($row['email_1']) ?></a></div>
-                            <?php endif; ?>
-                            <?php if(!empty($row['email_2'])): ?>
-                                <div><a href="mailto:<?= htmlspecialcharsFix($row['email_2']) ?>"><?= htmlspecialcharsFix($row['email_2']) ?></a></div>
-                            <?php endif; ?>
-                            <?php if(!empty($row['email_3'])): ?>
-                                <div><a href="mailto:<?= htmlspecialcharsFix($row['email_3']) ?>"><?= htmlspecialcharsFix($row['email_3']) ?></a></div>
-                            <?php endif; ?>
-                        </div>
-                        <div class="whatsapp">
-                            <?php if(!empty($row['whatsapp_1'])): ?>
-                                <div><?= htmlspecialcharsFix($row['whatsapp_1']) ?></div>
-                            <?php endif; ?>
-                            <?php if(!empty($row['whatsapp_2'])): ?>
-                                <div><?= htmlspecialcharsFix($row['whatsapp_2']) ?></div>
-                            <?php endif; ?>
-                            <?php if(!empty($row['whatsapp_3'])): ?>
-                                <div><?= htmlspecialcharsFix($row['whatsapp_3']) ?></div>
-                            <?php endif; ?>
-                        </div>
-                        <div class="wechat">
-                            <?php if(!empty($row['wechat_1'])): ?>
-                                <div><?= htmlspecialcharsFix($row['wechat_1']) ?></div>
-                            <?php endif; ?>
-                            <?php if(!empty($row['wechat_2'])): ?>
-                                <div><?= htmlspecialcharsFix($row['wechat_2']) ?></div>
-                            <?php endif; ?>
-                            <?php if(!empty($row['wechat_3'])): ?>
-                                <div><?= htmlspecialcharsFix($row['wechat_3']) ?></div>
-                            <?php endif; ?>
-                        </div>
-                        <div class="linkedin">
-                            <?php if(!empty($row['linkedin_1'])): ?>
-                                <div><?= htmlspecialcharsFix($row['linkedin_1']) ?></div>
-                            <?php endif; ?>
-                            <?php if(!empty($row['linkedin_2'])): ?>
-                                <div><?= htmlspecialcharsFix($row['linkedin_2']) ?></div>
-                            <?php endif; ?>
-                            <?php if(!empty($row['linkedin_3'])): ?>
-                                <div><?= htmlspecialcharsFix($row['linkedin_3']) ?></div>
-                            <?php endif; ?>
-                        </div>
-                        <div class="facebook">
-                            <?php if(!empty($row['facebook_1'])): ?>
-                                <div><?= htmlspecialcharsFix($row['facebook_1']) ?></div>
-                            <?php endif; ?>
-                            <?php if(!empty($row['facebook_2'])): ?>
-                                <div><?= htmlspecialcharsFix($row['facebook_2']) ?></div>
-                            <?php endif; ?>
-                            <?php if(!empty($row['facebook_3'])): ?>
-                                <div><?= htmlspecialcharsFix($row['facebook_3']) ?></div>
-                            <?php endif; ?>
-                        </div>
-                        <div class="alibaba">
-                            <?php if(!empty($row['alibaba_1'])): ?>
-                                <div><?= htmlspecialcharsFix($row['alibaba_1']) ?></div>
-                            <?php endif; ?>
-                            <?php if(!empty($row['alibaba_2'])): ?>
-                                <div><?= htmlspecialcharsFix($row['alibaba_2']) ?></div>
-                            <?php endif; ?>
-                            <?php if(!empty($row['alibaba_3'])): ?>
-                                <div><?= htmlspecialcharsFix($row['alibaba_3']) ?></div>
-                            <?php endif; ?>
-                        </div>
+                        <?php 
+                        // 展示联系人信息
+                        if ($contactData) {
+                            $contactFields = [
+                                'tel' => ['电话', false],
+                                'email' => ['邮箱', true],
+                                'whatsapp' => ['WhatsApp', false],
+                                'wechat' => ['微信', false],
+                                'linkedin' => ['领英', false],
+                                'facebook' => ['Facebook', false],
+                                'alibaba' => ['阿里巴巴', false]
+                            ];
+                            
+                            foreach ($contactFields as $fieldBase => $config) {
+                                $fieldName = $config[0];
+                                $isEmail = $config[1];
+                                
+                                echo "<div class=\"$fieldBase\">";
+                                for ($i = 1; $i <= 3; $i++) {
+                                    $field = $fieldBase . '_' . $i;
+                                    if (!empty($contactData[$field])) {
+                                        if ($isEmail) {
+                                            echo "<div><a href=\"mailto:" . htmlspecialcharsFix($contactData[$field]) . "\">" . 
+                                                 htmlspecialcharsFix($contactData[$field]) . "</a></div>";
+                                        } else {
+                                            echo "<div>" . htmlspecialcharsFix($contactData[$field]) . "</div>";
+                                        }
+                                    }
+                                }
+                                echo "</div>";
+                            }
+                        }
+                        ?>
                     </div>
                     <div class="noteItem2">备注</div>
                     <div class="notecontent"><?= htmlUnCode($row['cs_note']) ?></div>

+ 15 - 0
subTagClound.php

@@ -1,6 +1,21 @@
 <?php
 require_once 'conn.php';
 checkLogin();
+
+// 检查当前用户是否为组长
+$isLeader = false;
+$userInfoQuery = "SELECT em_role, em_permission_role_id FROM employee WHERE id = " . $_SESSION['employee_id'];
+$userResult = $conn->query($userInfoQuery);
+if ($userResult && $userRow = $userResult->fetch_assoc()) {
+    // 只有 em_permission_role_id=2 表示该用户是组长
+    $isLeader = ($userRow['em_permission_role_id'] == 2);
+}
+
+// 如果不是组长,直接跳转到客户列表页面
+if (!$isLeader) {
+    header('Location: customers.php');
+    exit;
+}
 ?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">