monthly_deal_stats.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. <?php
  2. /**
  3. * 每月新增成交客户统计分析
  4. */
  5. require_once 'conn.php';
  6. require_once 'statistics_utils.php';
  7. require_once 'statistics_customers.php';
  8. require_once 'statistics_sales.php';
  9. // 检查登录状态
  10. if (!isset($_SESSION['employee_id'])) {
  11. checkLogin();
  12. }
  13. function formatCurrency($value) {
  14. return '¥' . number_format($value ?? 0, 2);
  15. }
  16. // 获取当前登录用户信息
  17. $current_employee_id = $_SESSION['employee_id'];
  18. $current_permission_role = 0;
  19. // 获取当前用户权限角色
  20. $current_employee_id = intval($current_employee_id); // 确保是整数
  21. $query = "SELECT em_permission_role_id FROM employee WHERE id = $current_employee_id";
  22. $result = $conn->query($query);
  23. if ($result && $row = $result->fetch_assoc()) {
  24. $current_permission_role = $row['em_permission_role_id'];
  25. }
  26. // 检查是否为导出请求
  27. $is_export = isset($_GET['export']) && $_GET['export'] == 'excel';
  28. // 如果是导出请求但当前用户不是管理员,则拒绝导出
  29. if ($is_export && $current_permission_role != 1) {
  30. // 不允许导出,重定向回当前页面(不带export参数)
  31. $redirect_url = strtok($_SERVER['REQUEST_URI'], '?') . '?' . http_build_query(array_diff_key($_GET, ['export' => '', 'type' => '']));
  32. echo "<script>alert('只有管理员才有权限导出数据'); window.location.href='$redirect_url';</script>";
  33. exit;
  34. }
  35. // 获取日期范围参数
  36. $date_params = getDateRangeParams();
  37. $start_date = $date_params['start_date_sql'];
  38. $end_date = $date_params['end_date_sql'];
  39. $date_range = $date_params['date_range'];
  40. $period = $date_params['period'];
  41. // 如果不是导出操作,则包含页面头部
  42. if (!$is_export) {
  43. include('statistics_header.php');
  44. }
  45. /**
  46. * 获取每月新增成交客户数量
  47. */
  48. function getMonthlyDealCustomers($conn, $start_date, $end_date, $employee_filter = null) {
  49. $sql = "SELECT
  50. DATE_FORMAT(cs_dealdate, '%Y-%m') AS month,
  51. COUNT(*) AS customer_count
  52. FROM customer
  53. WHERE cs_dealdate BETWEEN '$start_date' AND '$end_date'
  54. AND cs_deal = 3";
  55. // 根据员工过滤条件添加WHERE子句
  56. if ($employee_filter !== null) {
  57. if (is_array($employee_filter)) {
  58. if (!empty($employee_filter)) {
  59. $employee_ids = implode(',', array_map('intval', $employee_filter));
  60. $sql .= " AND cs_belong IN ($employee_ids)";
  61. }
  62. } else {
  63. $sql .= " AND cs_belong = " . intval($employee_filter);
  64. }
  65. }
  66. $sql .= " GROUP BY DATE_FORMAT(cs_dealdate, '%Y-%m')
  67. ORDER BY month";
  68. $result = $conn->query($sql);
  69. $data = [];
  70. if ($result) {
  71. while ($row = $result->fetch_assoc()) {
  72. $data[] = $row;
  73. }
  74. }
  75. return $data;
  76. }
  77. /**
  78. * 获取按业务员统计的成交客户数量和金额
  79. */
  80. function getDealStatsByEmployee($conn, $start_date, $end_date, $employee_filter = null) {
  81. $sql = "SELECT
  82. e.id AS employee_id,
  83. e.em_user AS employee_name,
  84. COUNT(DISTINCT c.id) AS customer_count,
  85. SUM(o.total_amount) AS total_amount
  86. FROM orders o
  87. JOIN customer c ON o.customer_id = c.id
  88. JOIN employee e ON c.cs_belong = e.id
  89. WHERE o.order_date BETWEEN '$start_date' AND '$end_date'
  90. AND c.cs_deal = 3
  91. AND c.cs_dealdate BETWEEN '$start_date' AND '$end_date'";
  92. // 根据员工过滤条件添加WHERE子句
  93. if ($employee_filter !== null) {
  94. if (is_array($employee_filter)) {
  95. if (!empty($employee_filter)) {
  96. $employee_ids = implode(',', array_map('intval', $employee_filter));
  97. $sql .= " AND c.cs_belong IN ($employee_ids)";
  98. }
  99. } else {
  100. $sql .= " AND c.cs_belong = " . intval($employee_filter);
  101. }
  102. }
  103. $sql .= " GROUP BY e.id
  104. ORDER BY total_amount DESC";
  105. $result = $conn->query($sql);
  106. $data = [];
  107. if ($result) {
  108. while ($row = $result->fetch_assoc()) {
  109. $data[] = $row;
  110. }
  111. }
  112. return $data;
  113. }
  114. /**
  115. * 导出数据为CSV
  116. */
  117. function exportToCSV($data, $columns, $filename) {
  118. // 设置头信息
  119. header('Content-Type: text/csv; charset=utf-8');
  120. header('Content-Disposition: attachment;filename="' . $filename . '.csv"');
  121. header('Cache-Control: max-age=0');
  122. // 创建输出流
  123. $output = fopen('php://output', 'w');
  124. // 添加UTF-8 BOM以确保Excel正确显示中文
  125. fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
  126. // 输出列头
  127. fputcsv($output, $columns);
  128. // 输出数据行
  129. foreach ($data as $row) {
  130. // 确保所有数据都是数组格式
  131. $rowData = array_values($row);
  132. fputcsv($output, $rowData);
  133. }
  134. fclose($output);
  135. exit;
  136. }
  137. /**
  138. * 渲染每月成交客户数量表格
  139. */
  140. function renderMonthlyDealCustomersTable($data, $is_export = false) {
  141. if (empty($data)) {
  142. if (!$is_export) {
  143. echo '<div class="alert alert-info">当前选择范围内没有成交客户数据</div>';
  144. }
  145. return;
  146. }
  147. // 准备数据
  148. $table_data = [];
  149. $total_customers = 0;
  150. foreach ($data as $item) {
  151. $table_data[] = [
  152. '月份' => $item['month'],
  153. '新增成交客户数量' => $item['customer_count']
  154. ];
  155. $total_customers += intval($item['customer_count']);
  156. }
  157. // 如果是导出请求,则导出数据
  158. if ($is_export) {
  159. exportToCSV(
  160. $table_data,
  161. ['月份', '新增成交客户数量'],
  162. '每月新增成交客户数量_' . date('Ymd')
  163. );
  164. return;
  165. }
  166. // 渲染表格
  167. echo '<div class="row mt-5 mb-5">';
  168. echo '<div class="col-md-12">';
  169. echo '<div class="card">';
  170. echo '<div class="card-header d-flex justify-content-between align-items-center">';
  171. echo '<span>每月新增成交客户数量明细 (总计: '.$total_customers.' 客户)</span>';
  172. // 只有管理员才显示导出按钮
  173. if ($GLOBALS['current_permission_role'] == 1) {
  174. echo '<a href="' . $_SERVER['REQUEST_URI'] . '&export=excel&type=customers" class="btn btn-sm btn-success ml-3">导出CSV</a>';
  175. }
  176. echo '</div>';
  177. echo '<div class="card-body">';
  178. echo '<div class="table-responsive">';
  179. echo '<table class="table table-bordered table-striped">';
  180. echo '<thead class="thead-light">';
  181. echo '<tr>';
  182. echo '<th style="width: 50%; text-align: left;">月份</th>';
  183. echo '<th style="width: 50%; text-align: left;">新增成交客户数量</th>';
  184. echo '</tr>';
  185. echo '</thead>';
  186. echo '<tbody>';
  187. foreach ($data as $item) {
  188. echo '<tr>';
  189. echo '<td>'.$item['month'].'</td>';
  190. echo '<td>'.$item['customer_count'].'</td>';
  191. echo '</tr>';
  192. }
  193. echo '</tbody>';
  194. echo '</table>';
  195. echo '</div>';
  196. echo '</div>';
  197. echo '</div>';
  198. echo '</div>';
  199. echo '</div>';
  200. }
  201. /**
  202. * 渲染业务员成交统计表格
  203. */
  204. function renderDealStatsByEmployeeTable($data, $is_export = false) {
  205. if (empty($data)) {
  206. if (!$is_export) {
  207. echo '<div class="alert alert-info">当前选择范围内没有业务员成交数据</div>';
  208. }
  209. return;
  210. }
  211. // 准备数据
  212. $table_data = [];
  213. foreach ($data as $item) {
  214. $avg_customer_value = $item['customer_count'] > 0 ? $item['total_amount'] / $item['customer_count'] : 0;
  215. $table_data[] = [
  216. '业务员' => $item['employee_name'],
  217. '成交客户数' => $item['customer_count'],
  218. '成交金额' => $is_export ? $item['total_amount'] : formatCurrency($item['total_amount']),
  219. '客单价' => $is_export ? $avg_customer_value : formatCurrency($avg_customer_value)
  220. ];
  221. }
  222. // 如果是导出请求,则导出数据
  223. if ($is_export) {
  224. exportToCSV(
  225. $table_data,
  226. ['业务员', '成交客户数', '成交金额', '客单价'],
  227. '业务员成交统计_' . date('Ymd')
  228. );
  229. return;
  230. }
  231. // 渲染表格
  232. echo '<div class="row mt-5">';
  233. echo '<div class="col-md-12">';
  234. echo '<div class="card">';
  235. echo '<div class="card-header d-flex justify-content-between align-items-center">';
  236. echo '<span>业务员成交统计明细</span>';
  237. // 只有管理员才显示导出按钮
  238. if ($GLOBALS['current_permission_role'] == 1) {
  239. echo '<a href="' . $_SERVER['REQUEST_URI'] . '&export=excel&type=employee" class="btn btn-sm btn-success ml-3">导出CSV</a>';
  240. }
  241. echo '</div>';
  242. echo '<div class="card-body">';
  243. echo '<div class="table-responsive">';
  244. echo '<table class="table table-bordered table-striped">';
  245. echo '<thead class="thead-light">';
  246. echo '<tr>';
  247. echo '<th style="width: 25%; text-align: left;">业务员</th>';
  248. echo '<th style="width: 25%; text-align: left;">成交客户数</th>';
  249. echo '<th style="width: 25%; text-align: left;">成交金额</th>';
  250. echo '<th style="width: 25%; text-align: left;">客单价</th>';
  251. echo '</tr>';
  252. echo '</thead>';
  253. echo '<tbody>';
  254. foreach ($data as $item) {
  255. $avg_customer_value = $item['customer_count'] > 0 ? $item['total_amount'] / $item['customer_count'] : 0;
  256. echo '<tr>';
  257. echo '<td>'.$item['employee_name'].'</td>';
  258. echo '<td>'.$item['customer_count'].'</td>';
  259. echo '<td>'.formatCurrency($item['total_amount']).'</td>';
  260. echo '<td>'.formatCurrency($avg_customer_value).'</td>';
  261. echo '</tr>';
  262. }
  263. echo '</tbody>';
  264. echo '</table>';
  265. echo '</div>';
  266. echo '</div>';
  267. echo '</div>';
  268. echo '</div>';
  269. echo '</div>';
  270. }
  271. // 获取选择的业务员
  272. $selected_employee = isset($_GET['selected_employee']) ? $_GET['selected_employee'] : 'all';
  273. // 确定要显示哪些业务员的数据
  274. $employee_filter = null;
  275. if ($selected_employee != 'all') {
  276. // 如果选择了特定业务员,则只显示该业务员的数据
  277. $employee_filter = intval($selected_employee);
  278. } else {
  279. // 否则按权限显示相应的业务员数据
  280. if ($current_permission_role == 1) {
  281. // 管理员可以看到所有业务员
  282. $employee_filter = null;
  283. } elseif ($current_permission_role == 2) {
  284. // 组长可以看到自己和组员
  285. $visible_employees = [];
  286. $query = "SELECT id FROM employee WHERE id = " . intval($current_employee_id) . " OR em_role = " . intval($current_employee_id);
  287. $result = $conn->query($query);
  288. if ($result) {
  289. while ($row = $result->fetch_assoc()) {
  290. $visible_employees[] = $row['id'];
  291. }
  292. }
  293. $employee_filter = $visible_employees;
  294. } else {
  295. // 组员只能看到自己
  296. $employee_filter = intval($current_employee_id);
  297. }
  298. }
  299. // 获取每月新增成交客户数量数据
  300. $monthly_deal_customers = getMonthlyDealCustomers($conn, $start_date, $end_date, $employee_filter);
  301. // 获取业务员成交统计数据
  302. $deal_stats_by_employee = getDealStatsByEmployee($conn, $start_date, $end_date, $employee_filter);
  303. // 处理导出请求
  304. if ($is_export) {
  305. $export_type = isset($_GET['type']) ? $_GET['type'] : '';
  306. switch ($export_type) {
  307. case 'customers':
  308. renderMonthlyDealCustomersTable($monthly_deal_customers, true);
  309. break;
  310. case 'employee':
  311. renderDealStatsByEmployeeTable($deal_stats_by_employee, true);
  312. break;
  313. }
  314. exit; // 确保导出后停止执行
  315. }
  316. ?>
  317. <div class="container">
  318. <div class="page-header">
  319. <h1 class="page-title">每月新增成交客户统计</h1>
  320. </div>
  321. <!-- 日期筛选 -->
  322. <div class="filter-form mb-5">
  323. <form method="get" class="filter-form-inline">
  324. <div class="form-group mr-3">
  325. <label for="date_range" class="mr-2">选择日期范围</label>
  326. <select class="form-control" id="date_range" name="date_range" onchange="toggleCustomDates()">
  327. <option value="current_month" <?php echo $date_range == 'current_month' ? 'selected' : ''; ?>>本月</option>
  328. <option value="last_month" <?php echo $date_range == 'last_month' ? 'selected' : ''; ?>>上月</option>
  329. <option value="current_year" <?php echo $date_range == 'current_year' ? 'selected' : ''; ?>>今年</option>
  330. <option value="last_30_days" <?php echo $date_range == 'last_30_days' ? 'selected' : ''; ?>>最近30天</option>
  331. <option value="last_90_days" <?php echo $date_range == 'last_90_days' ? 'selected' : ''; ?>>最近90天</option>
  332. <option value="custom" <?php echo $date_range == 'custom' ? 'selected' : ''; ?>>自定义日期范围</option>
  333. </select>
  334. </div>
  335. <div class="form-group custom-date-inputs mr-3" id="custom_start_date" style="display: <?php echo $date_range == 'custom' ? 'inline-block' : 'none'; ?>">
  336. <label for="start_date" class="mr-2">开始日期</label>
  337. <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo $date_params['custom_start']; ?>">
  338. </div>
  339. <div class="form-group custom-date-inputs mr-3" id="custom_end_date" style="display: <?php echo $date_range == 'custom' ? 'inline-block' : 'none'; ?>">
  340. <label for="end_date" class="mr-2">结束日期</label>
  341. <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo $date_params['custom_end']; ?>">
  342. </div>
  343. <!-- 业务员选择 -->
  344. <div class="form-group mr-3">
  345. <label for="selected_employee" class="mr-2">选择业务员</label>
  346. <select class="form-control" id="selected_employee" name="selected_employee">
  347. <option value="all">所有业务员</option>
  348. <?php
  349. // 获取当前用户可见的业务员列表
  350. $visible_employees_query = "";
  351. if ($current_permission_role == 1) {
  352. // 管理员可以看到所有业务员
  353. $visible_employees_query = "SELECT id, em_user FROM employee WHERE em_role IS NOT NULL ORDER BY em_user";
  354. } elseif ($current_permission_role == 2) {
  355. // 组长可以看到自己和组员
  356. $visible_employees_query = "SELECT id, em_user FROM employee WHERE id = $current_employee_id OR em_role = $current_employee_id ORDER BY em_user";
  357. } else {
  358. // 组员只能看到自己
  359. $visible_employees_query = "SELECT id, em_user FROM employee WHERE id = $current_employee_id";
  360. }
  361. $visible_employees_result = $conn->query($visible_employees_query);
  362. $selected_employee = isset($_GET['selected_employee']) ? $_GET['selected_employee'] : 'all';
  363. while ($emp = $visible_employees_result->fetch_assoc()) {
  364. $selected = ($selected_employee == $emp['id']) ? 'selected' : '';
  365. echo "<option value='".$emp['id']."' $selected>".$emp['em_user']."</option>";
  366. }
  367. ?>
  368. </select>
  369. </div>
  370. <div class="form-group">
  371. <button type="submit" class="btn btn-primary">应用筛选</button>
  372. </div>
  373. </form>
  374. </div>
  375. <!-- 统计内容区域 -->
  376. <div class="stats-content">
  377. <?php
  378. // 渲染表格
  379. renderMonthlyDealCustomersTable($monthly_deal_customers);
  380. renderDealStatsByEmployeeTable($deal_stats_by_employee);
  381. ?>
  382. </div>
  383. </div>
  384. <style>
  385. /* 添加一些额外的样式以改善表格显示 */
  386. .filter-form {
  387. background-color: #f8f9fa;
  388. padding: 20px;
  389. border-radius: 5px;
  390. margin-bottom: 30px;
  391. }
  392. .filter-form-inline {
  393. display: flex;
  394. flex-wrap: wrap;
  395. align-items: flex-end;
  396. }
  397. .filter-form .form-group {
  398. margin-bottom: 10px;
  399. margin-right: 15px;
  400. }
  401. /* 表格样式 */
  402. .table {
  403. width: 100%;
  404. margin-bottom: 1rem;
  405. }
  406. .table th, .table td {
  407. padding: 12px;
  408. vertical-align: middle;
  409. }
  410. /* 确保表头也是左对齐 */
  411. .thead-light th {
  412. background-color: #f8f9fa;
  413. border-color: #dee2e6;
  414. text-align: left;
  415. }
  416. .table-striped tbody tr:nth-of-type(odd) {
  417. background-color: rgba(0, 0, 0, 0.03);
  418. }
  419. .card {
  420. box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
  421. }
  422. .card-header {
  423. background-color: #f8f9fa;
  424. padding: 15px;
  425. }
  426. .card-body {
  427. padding: 1.5rem;
  428. }
  429. /* 添加按钮左边距 */
  430. .ml-3 {
  431. margin-left: 15px !important;
  432. }
  433. /* 确保卡片头部布局正确 */
  434. .card-header.d-flex {
  435. display: flex !important;
  436. justify-content: space-between !important;
  437. align-items: center !important;
  438. }
  439. </style>
  440. <script>
  441. function toggleCustomDates() {
  442. const dateRange = document.getElementById('date_range').value;
  443. const customDateInputs = document.querySelectorAll('.custom-date-inputs');
  444. if (dateRange === 'custom') {
  445. customDateInputs.forEach(el => el.style.display = 'inline-block');
  446. } else {
  447. customDateInputs.forEach(el => el.style.display = 'none');
  448. }
  449. }
  450. </script>
  451. <?php
  452. // 页面底部
  453. include('statistics_footer.php');
  454. ?>