statistics_utils.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. <?php
  2. /**
  3. * 统计分析工具函数
  4. *
  5. * 包含所有统计模块共用的工具函数和日期处理逻辑
  6. */
  7. // 确保直接访问时需要先登录
  8. require_once 'conn.php';
  9. if (!isset($_SESSION['employee_id'])) {
  10. checkLogin();
  11. }
  12. //检查是否管理员
  13. checkPermissionDie(1,2);
  14. /**
  15. * 获取和处理日期范围参数
  16. *
  17. * @return array 包含开始日期、结束日期和其他日期相关参数
  18. */
  19. function getDateRangeParams() {
  20. // 计算日期范围
  21. $current_month_start = date('Y-m-01');
  22. $current_month_end = date('Y-m-t');
  23. $last_month_start = date('Y-m-01', strtotime('-1 month'));
  24. $last_month_end = date('Y-m-t', strtotime('-1 month'));
  25. $current_year_start = date('Y-01-01');
  26. $current_year_end = date('Y-12-31');
  27. // 可选的日期范围筛选
  28. $date_range = isset($_GET['date_range']) ? $_GET['date_range'] : 'current_month';
  29. $custom_start = isset($_GET['start_date']) ? $_GET['start_date'] : '';
  30. $custom_end = isset($_GET['end_date']) ? $_GET['end_date'] : '';
  31. $period = isset($_GET['period']) ? $_GET['period'] : 'day';
  32. // 设置日期范围
  33. if ($date_range == 'custom' && !empty($custom_start) && !empty($custom_end)) {
  34. $start_date = $custom_start;
  35. $end_date = $custom_end;
  36. } else {
  37. switch ($date_range) {
  38. case 'last_month':
  39. $start_date = $last_month_start;
  40. $end_date = $last_month_end;
  41. break;
  42. case 'current_year':
  43. $start_date = $current_year_start;
  44. $end_date = $current_year_end;
  45. break;
  46. case 'last_30_days':
  47. $start_date = date('Y-m-d', strtotime('-30 days'));
  48. $end_date = date('Y-m-d');
  49. break;
  50. case 'last_90_days':
  51. $start_date = date('Y-m-d', strtotime('-90 days'));
  52. $end_date = date('Y-m-d');
  53. break;
  54. case 'current_month':
  55. default:
  56. $start_date = $current_month_start;
  57. $end_date = $current_month_end;
  58. break;
  59. }
  60. }
  61. // 格式化日期用于SQL查询
  62. $start_date_sql = date('Y-m-d', strtotime($start_date));
  63. $end_date_sql = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
  64. return [
  65. 'date_range' => $date_range,
  66. 'custom_start' => $custom_start,
  67. 'custom_end' => $custom_end,
  68. 'period' => $period,
  69. 'start_date' => $start_date,
  70. 'end_date' => $end_date,
  71. 'start_date_sql' => $start_date_sql,
  72. 'end_date_sql' => $end_date_sql
  73. ];
  74. }
  75. /**
  76. * 生成图表颜色数组
  77. *
  78. * @param int $count 需要的颜色数量
  79. * @param bool $transparent 是否透明
  80. * @return array 背景色和边框色数组
  81. */
  82. function generateChartColors($count = 10, $transparent = true) {
  83. $colors = [
  84. ['rgba(255, 99, 132, ' . ($transparent ? '0.7' : '1') . ')', 'rgba(255, 99, 132, 1)'],
  85. ['rgba(54, 162, 235, ' . ($transparent ? '0.7' : '1') . ')', 'rgba(54, 162, 235, 1)'],
  86. ['rgba(255, 206, 86, ' . ($transparent ? '0.7' : '1') . ')', 'rgba(255, 206, 86, 1)'],
  87. ['rgba(75, 192, 192, ' . ($transparent ? '0.7' : '1') . ')', 'rgba(75, 192, 192, 1)'],
  88. ['rgba(153, 102, 255, ' . ($transparent ? '0.7' : '1') . ')', 'rgba(153, 102, 255, 1)'],
  89. ['rgba(255, 159, 64, ' . ($transparent ? '0.7' : '1') . ')', 'rgba(255, 159, 64, 1)'],
  90. ['rgba(199, 199, 199, ' . ($transparent ? '0.7' : '1') . ')', 'rgba(199, 199, 199, 1)'],
  91. ['rgba(83, 102, 255, ' . ($transparent ? '0.7' : '1') . ')', 'rgba(83, 102, 255, 1)'],
  92. ['rgba(40, 159, 64, ' . ($transparent ? '0.7' : '1') . ')', 'rgba(40, 159, 64, 1)'],
  93. ['rgba(210, 199, 199, ' . ($transparent ? '0.7' : '1') . ')', 'rgba(210, 199, 199, 1)']
  94. ];
  95. $result = [];
  96. // 确保有足够的颜色
  97. while (count($result) < $count) {
  98. foreach ($colors as $color) {
  99. $result[] = $color;
  100. if (count($result) >= $count) {
  101. break;
  102. }
  103. }
  104. }
  105. return array_slice($result, 0, $count);
  106. }
  107. /**
  108. * 格式化数值,处理空值和小数位数
  109. *
  110. * @param mixed $value 要格式化的值
  111. * @param int $decimals 小数位数
  112. * @return string 格式化后的数值
  113. */
  114. function formatNumber($value, $decimals = 2) {
  115. if ($value === null || $value === '') {
  116. return '0';
  117. }
  118. return number_format((float)$value, $decimals);
  119. }
  120. /**
  121. * 获取时间粒度对应的MySQL DATE_FORMAT格式
  122. *
  123. * @param string $period 时间粒度 (day/week/month)
  124. * @return string MySQL DATE_FORMAT格式字符串
  125. */
  126. function getPeriodFormat($period) {
  127. switch ($period) {
  128. case 'week':
  129. return '%x-W%v'; // ISO year and week number
  130. case 'month':
  131. return '%Y-%m';
  132. case 'day':
  133. default:
  134. return '%Y-%m-%d';
  135. }
  136. }
  137. /**
  138. * 获取新增客户详细信息
  139. *
  140. * @param mysqli $conn 数据库连接
  141. * @param string $start_date 开始日期
  142. * @param string $end_date 结束日期
  143. * @param array|int $employee_filter 业务员ID或ID数组,用于过滤数据 (可选)
  144. * @return array 新增客户详细数据
  145. */
  146. function getNewCustomersDetails($conn, $start_date, $end_date, $employee_filter = null) {
  147. // 使用 mysqli_real_escape_string 防止 SQL 注入
  148. $start_date = $conn->real_escape_string($start_date);
  149. $end_date = $conn->real_escape_string($end_date);
  150. $sql = "SELECT
  151. c.id,
  152. c.cs_company as company_name,
  153. c.cs_code as customer_code,
  154. co.countryName as country,
  155. ct.businessType as customer_type,
  156. e.em_user as employee_name,
  157. c.cs_addtime as add_date
  158. FROM customer c
  159. LEFT JOIN country co ON c.cs_country = co.id
  160. LEFT JOIN clienttype ct ON c.cs_type = ct.id
  161. LEFT JOIN employee e ON c.cs_belong = e.id
  162. WHERE c.cs_addtime BETWEEN '$start_date' AND '$end_date'";
  163. // 如果有业务员过滤条件
  164. if ($employee_filter !== null) {
  165. if (is_array($employee_filter) && !empty($employee_filter)) {
  166. // 处理数组形式的业务员ID列表
  167. $emp_ids = array();
  168. foreach ($employee_filter as $emp_id) {
  169. if (is_numeric($emp_id)) {
  170. $emp_ids[] = intval($emp_id);
  171. }
  172. }
  173. if (!empty($emp_ids)) {
  174. $emp_ids_str = implode(',', $emp_ids);
  175. $sql .= " AND c.cs_belong IN ($emp_ids_str)";
  176. }
  177. } else if (is_numeric($employee_filter) && $employee_filter > 0) {
  178. // 处理单个业务员ID
  179. $employee_filter = intval($employee_filter);
  180. $sql .= " AND c.cs_belong = $employee_filter";
  181. }
  182. }
  183. $sql .= " ORDER BY c.cs_addtime DESC LIMIT 30";
  184. $result = $conn->query($sql);
  185. $customers = [];
  186. if ($result) {
  187. while ($row = $result->fetch_assoc()) {
  188. $customers[] = $row;
  189. }
  190. }
  191. return $customers;
  192. }
  193. /**
  194. * 获取各业务员新增客户统计
  195. *
  196. * @param mysqli $conn 数据库连接
  197. * @param string $start_date 开始日期
  198. * @param string $end_date 结束日期
  199. * @param array $visible_employees 可见的业务员ID列表 (可选)
  200. * @return array 业务员新增客户统计数据
  201. */
  202. function getNewCustomersByEmployee($conn, $start_date, $end_date, $visible_employees = null) {
  203. // 使用 mysqli_real_escape_string 防止 SQL 注入
  204. $start_date = $conn->real_escape_string($start_date);
  205. $end_date = $conn->real_escape_string($end_date);
  206. $sql = "SELECT
  207. e.id as employee_id,
  208. e.em_user as employee_name,
  209. COUNT(c.id) as customer_count
  210. FROM employee e
  211. LEFT JOIN customer c ON e.id = c.cs_belong AND c.cs_addtime BETWEEN '$start_date' AND '$end_date'
  212. WHERE e.em_role IS NOT NULL";
  213. // 如果指定了可见业务员列表,则添加过滤条件
  214. if ($visible_employees !== null && !empty($visible_employees)) {
  215. $emp_ids = array();
  216. foreach ($visible_employees as $emp_id) {
  217. if (is_numeric($emp_id)) {
  218. $emp_ids[] = intval($emp_id);
  219. }
  220. }
  221. if (!empty($emp_ids)) {
  222. $emp_ids_str = implode(',', $emp_ids);
  223. $sql .= " AND e.id IN ($emp_ids_str)";
  224. }
  225. }
  226. $sql .= " GROUP BY e.id ORDER BY customer_count DESC";
  227. $result = $conn->query($sql);
  228. $data = [];
  229. if ($result) {
  230. while ($row = $result->fetch_assoc()) {
  231. $data[] = $row;
  232. }
  233. }
  234. return $data;
  235. }
  236. /**
  237. * 渲染新增客户图表
  238. *
  239. * @param array $customers 新增客户数据
  240. * @return void
  241. */
  242. function renderNewCustomersChart($customers) {
  243. if (empty($customers)) {
  244. echo '<div class="alert alert-info">该时间段内没有新增客户数据</div>';
  245. return;
  246. }
  247. ?>
  248. <div class="chart-container">
  249. <div class="table-responsive">
  250. <table class="data-table">
  251. <thead>
  252. <tr>
  253. <th>客户名称</th>
  254. <th>客户编码</th>
  255. <th>国家/地区</th>
  256. <th>客户类型</th>
  257. <th>负责业务员</th>
  258. <th>添加日期</th>
  259. </tr>
  260. </thead>
  261. <tbody>
  262. <?php foreach ($customers as $customer): ?>
  263. <tr>
  264. <td><?php echo htmlspecialcharsFix($customer['company_name']); ?></td>
  265. <td><?php echo htmlspecialcharsFix($customer['customer_code']); ?></td>
  266. <td><?php echo htmlspecialcharsFix($customer['country']); ?></td>
  267. <td><?php echo htmlspecialcharsFix($customer['customer_type'] ?: '未分类'); ?></td>
  268. <td><?php echo htmlspecialcharsFix($customer['employee_name']); ?></td>
  269. <td><?php echo date('Y-m-d', strtotime($customer['add_date'])); ?></td>
  270. </tr>
  271. <?php endforeach; ?>
  272. </tbody>
  273. </table>
  274. </div>
  275. </div>
  276. <script>
  277. // 准备图表数据
  278. <?php
  279. // 按日期分组客户数量
  280. $dates = [];
  281. $counts = [];
  282. $dateGroups = [];
  283. foreach ($customers as $customer) {
  284. $date = date('Y-m-d', strtotime($customer['add_date']));
  285. if (!isset($dateGroups[$date])) {
  286. $dateGroups[$date] = 0;
  287. }
  288. $dateGroups[$date]++;
  289. }
  290. // 排序日期
  291. ksort($dateGroups);
  292. foreach ($dateGroups as $date => $count) {
  293. $dates[] = $date;
  294. $counts[] = $count;
  295. }
  296. ?>
  297. </script>
  298. <?php
  299. }
  300. /**
  301. * 渲染业务员新增客户图表
  302. *
  303. * @param array $employee_data 业务员新增客户数据
  304. * @return void
  305. */
  306. function renderNewCustomersByEmployeeChart($employee_data) {
  307. if (empty($employee_data)) {
  308. echo '<div class="alert alert-info">该时间段内没有业务员新增客户数据</div>';
  309. return;
  310. }
  311. // 准备图表数据
  312. $employee_names = [];
  313. $customer_counts = [];
  314. foreach ($employee_data as $row) {
  315. $employee_names[] = $row['employee_name'];
  316. $customer_counts[] = $row['customer_count'];
  317. }
  318. // 生成图表背景色
  319. $colors = generateChartColors(count($employee_data));
  320. $backgroundColors = [];
  321. $borderColors = [];
  322. foreach ($colors as $color) {
  323. $backgroundColors[] = $color[0];
  324. $borderColors[] = $color[1];
  325. }
  326. ?>
  327. <div class="analysis-grid">
  328. <div>
  329. <canvas id="employeeNewCustomersChart"></canvas>
  330. </div>
  331. <div class="table-responsive">
  332. <table class="data-table">
  333. <thead>
  334. <tr>
  335. <th>业务员</th>
  336. <th>新增客户数量</th>
  337. </tr>
  338. </thead>
  339. <tbody>
  340. <?php foreach ($employee_data as $row): ?>
  341. <tr>
  342. <td><?php echo htmlspecialchars($row['employee_name']); ?></td>
  343. <td><?php echo number_format($row['customer_count']); ?></td>
  344. </tr>
  345. <?php endforeach; ?>
  346. </tbody>
  347. </table>
  348. </div>
  349. </div>
  350. <script>
  351. var employeeNewCustomersCtx = document.getElementById('employeeNewCustomersChart').getContext('2d');
  352. new Chart(employeeNewCustomersCtx, {
  353. type: 'bar',
  354. data: {
  355. labels: <?php echo json_encode($employee_names); ?>,
  356. datasets: [{
  357. label: '新增客户数量',
  358. data: <?php echo json_encode($customer_counts); ?>,
  359. backgroundColor: <?php echo json_encode($backgroundColors); ?>,
  360. borderColor: <?php echo json_encode($borderColors); ?>,
  361. borderWidth: 1
  362. }]
  363. },
  364. options: {
  365. responsive: true,
  366. scales: {
  367. y: {
  368. beginAtZero: true,
  369. title: {
  370. display: true,
  371. text: '客户数量'
  372. }
  373. }
  374. },
  375. plugins: {
  376. title: {
  377. display: true,
  378. text: '业务员新增客户统计'
  379. }
  380. }
  381. }
  382. });
  383. </script>
  384. <?php
  385. }
  386. /**
  387. * 根据用户角色获取可见的业务员列表
  388. *
  389. * @param mysqli $conn 数据库连接
  390. * @param int $user_id 当前用户ID
  391. * @return array 可访问的业务员ID和姓名列表
  392. */
  393. function getAccessibleEmployees($conn, $user_id) {
  394. // 获取当前用户信息
  395. $sql = "SELECT em_user, em_role FROM employee WHERE id = ?";
  396. $stmt = $conn->prepare($sql);
  397. $stmt->bind_param("i", $user_id);
  398. $stmt->execute();
  399. $result = $stmt->get_result();
  400. $user = $result->fetch_assoc();
  401. $role = $user['em_role'] ?? 0;
  402. $employees = [];
  403. if ($role == 1) {
  404. // 管理员可以看到所有业务员
  405. $sql = "SELECT id, em_user FROM employee WHERE em_role IS NOT NULL ORDER BY em_user";
  406. $result = $conn->query($sql);
  407. while ($row = $result->fetch_assoc()) {
  408. $employees[] = [
  409. 'id' => $row['id'],
  410. 'name' => $row['em_user']
  411. ];
  412. }
  413. } else if ($role == 2) {
  414. // 获取组长自己和其团队成员
  415. $sql = "SELECT id, em_user FROM employee WHERE id = ? OR em_role = ? ORDER BY em_user";
  416. $stmt = $conn->prepare($sql);
  417. $stmt->bind_param("ii", $user_id, $user_id);
  418. $stmt->execute();
  419. $result = $stmt->get_result();
  420. while ($row = $result->fetch_assoc()) {
  421. $employees[] = [
  422. 'id' => $row['id'],
  423. 'name' => $row['em_user']
  424. ];
  425. }
  426. } else {
  427. // 普通业务员只能看到自己
  428. $sql = "SELECT id, em_user FROM employee WHERE id = ?";
  429. $stmt = $conn->prepare($sql);
  430. $stmt->bind_param("i", $user_id);
  431. $stmt->execute();
  432. $result = $stmt->get_result();
  433. while ($row = $result->fetch_assoc()) {
  434. $employees[] = [
  435. 'id' => $row['id'],
  436. 'name' => $row['em_user']
  437. ];
  438. }
  439. }
  440. return $employees;
  441. }
  442. /**
  443. * 根据用户角色获取默认的业务员筛选列表
  444. *
  445. * @param mysqli $conn 数据库连接
  446. * @param int $user_id 当前用户ID
  447. * @return array|int|null 业务员筛选值,可能是单个ID、ID数组或null
  448. */
  449. function getDefaultEmployeeFilter($conn, $user_id) {
  450. // 获取当前用户角色
  451. $sql = "SELECT em_role FROM employee WHERE id = ?";
  452. $stmt = $conn->prepare($sql);
  453. $stmt->bind_param("i", $user_id);
  454. $stmt->execute();
  455. $result = $stmt->get_result();
  456. $user = $result->fetch_assoc();
  457. $role = $user['em_role'] ?? 0;
  458. if ($role == 1) {
  459. // 管理员默认看所有人
  460. return null;
  461. } else if ($role == 2) {
  462. // 团队组长默认看他的团队
  463. $sql = "SELECT id FROM employee WHERE id = ? OR em_role = ?";
  464. $stmt = $conn->prepare($sql);
  465. $stmt->bind_param("ii", $user_id, $user_id);
  466. $stmt->execute();
  467. $result = $stmt->get_result();
  468. $emp_ids = [];
  469. while ($row = $result->fetch_assoc()) {
  470. $emp_ids[] = $row['id'];
  471. }
  472. return $emp_ids;
  473. } else {
  474. // 普通业务员只看自己
  475. return $user_id;
  476. }
  477. }
  478. /**
  479. * 渲染新客户产品购买明细
  480. *
  481. * @param array $product_data 产品购买数据
  482. * @return void
  483. */
  484. function renderNewCustomerProductPurchases($product_data) {
  485. if (empty($product_data) || empty($product_data['products'])) {
  486. echo '<div class="alert alert-info">该时间段内没有新客户购买产品数据</div>';
  487. return;
  488. }
  489. $products = $product_data['products'];
  490. $new_customer_count = $product_data['new_customer_count'];
  491. ?>
  492. <div class="section-intro">
  493. <p>本期间共有 <strong><?php echo number_format($new_customer_count); ?></strong> 名新客户进行了购买。以下是他们购买的产品明细:</p>
  494. </div>
  495. <div class="table-responsive">
  496. <table class="data-table">
  497. <thead>
  498. <tr>
  499. <th>产品名称</th>
  500. <th>产品分类</th>
  501. <th>订单数</th>
  502. <th>购买客户数</th>
  503. <th>销售数量</th>
  504. <th>销售金额</th>
  505. <th>平均单价</th>
  506. </tr>
  507. </thead>
  508. <tbody>
  509. <?php foreach ($products as $product): ?>
  510. <tr>
  511. <td><?php echo htmlspecialchars($product['product_name']); ?></td>
  512. <td><?php echo htmlspecialchars($product['category_name'] ?: '未分类'); ?></td>
  513. <td><?php echo number_format($product['order_count']); ?></td>
  514. <td><?php echo number_format($product['customer_count']); ?></td>
  515. <td><?php echo number_format($product['total_quantity']); ?></td>
  516. <td><?php echo formatCurrency($product['total_revenue']); ?></td>
  517. <td><?php echo formatCurrency($product['avg_price']); ?></td>
  518. </tr>
  519. <?php endforeach; ?>
  520. </tbody>
  521. </table>
  522. </div>
  523. <!-- 新客户产品购买分布图 -->
  524. <div class="chart-container">
  525. <div>
  526. <canvas id="newCustomerProductChart"></canvas>
  527. </div>
  528. </div>
  529. <script>
  530. <?php
  531. // 准备图表数据
  532. $product_names = [];
  533. $product_quantities = [];
  534. $product_revenues = [];
  535. // 只取前10个产品用于图表显示
  536. $top_products = array_slice($products, 0, 10);
  537. foreach ($top_products as $product) {
  538. $product_names[] = $product['product_name'];
  539. $product_quantities[] = $product['total_quantity'];
  540. $product_revenues[] = $product['total_revenue'];
  541. }
  542. // 生成图表背景色
  543. $colors = generateChartColors(count($top_products));
  544. $backgroundColors = [];
  545. foreach ($colors as $color) {
  546. $backgroundColors[] = $color[0];
  547. }
  548. ?>
  549. var newCustomerProductCtx = document.getElementById('newCustomerProductChart').getContext('2d');
  550. new Chart(newCustomerProductCtx, {
  551. type: 'bar',
  552. data: {
  553. labels: <?php echo json_encode($product_names); ?>,
  554. datasets: [
  555. {
  556. label: '销售数量',
  557. data: <?php echo json_encode($product_quantities); ?>,
  558. backgroundColor: 'rgba(54, 162, 235, 0.7)',
  559. borderColor: 'rgba(54, 162, 235, 1)',
  560. borderWidth: 1,
  561. yAxisID: 'y-quantity'
  562. },
  563. {
  564. label: '销售金额',
  565. data: <?php echo json_encode($product_revenues); ?>,
  566. backgroundColor: 'rgba(255, 99, 132, 0.7)',
  567. borderColor: 'rgba(255, 99, 132, 1)',
  568. borderWidth: 1,
  569. yAxisID: 'y-revenue',
  570. type: 'line',
  571. fill: false
  572. }
  573. ]
  574. },
  575. options: {
  576. responsive: true,
  577. scales: {
  578. 'y-quantity': {
  579. type: 'linear',
  580. position: 'left',
  581. title: {
  582. display: true,
  583. text: '销售数量'
  584. },
  585. beginAtZero: true
  586. },
  587. 'y-revenue': {
  588. type: 'linear',
  589. position: 'right',
  590. title: {
  591. display: true,
  592. text: '销售金额'
  593. },
  594. beginAtZero: true,
  595. grid: {
  596. drawOnChartArea: false
  597. }
  598. }
  599. },
  600. plugins: {
  601. title: {
  602. display: true,
  603. text: '新客户热门购买产品 (Top 10)'
  604. }
  605. }
  606. }
  607. });
  608. </script>
  609. <!-- 新客户产品类别分布图 -->
  610. <div class="chart-container">
  611. <div>
  612. <canvas id="newCustomerCategoryChart"></canvas>
  613. </div>
  614. </div>
  615. <script>
  616. <?php
  617. // 按产品类别分组
  618. $categories = [];
  619. $category_data = [];
  620. foreach ($products as $product) {
  621. $category = $product['category_name'] ?: '未分类';
  622. if (!isset($category_data[$category])) {
  623. $category_data[$category] = [
  624. 'quantity' => 0,
  625. 'revenue' => 0
  626. ];
  627. }
  628. $category_data[$category]['quantity'] += $product['total_quantity'];
  629. $category_data[$category]['revenue'] += $product['total_revenue'];
  630. }
  631. $category_names = array_keys($category_data);
  632. $category_quantities = array_column($category_data, 'quantity');
  633. $category_revenues = array_column($category_data, 'revenue');
  634. // 计算占比
  635. $total_revenue = array_sum($category_revenues);
  636. $revenue_percentages = [];
  637. foreach ($category_revenues as $revenue) {
  638. $revenue_percentages[] = round(($revenue / $total_revenue) * 100, 1);
  639. }
  640. // 生成图表背景色
  641. $category_colors = generateChartColors(count($category_data), false);
  642. $category_bg_colors = array_column($category_colors, 0);
  643. ?>
  644. var newCustomerCategoryCtx = document.getElementById('newCustomerCategoryChart').getContext('2d');
  645. new Chart(newCustomerCategoryCtx, {
  646. type: 'pie',
  647. data: {
  648. labels: <?php echo json_encode($category_names); ?>,
  649. datasets: [{
  650. data: <?php echo json_encode($revenue_percentages); ?>,
  651. backgroundColor: <?php echo json_encode($category_bg_colors); ?>,
  652. borderWidth: 1
  653. }]
  654. },
  655. options: {
  656. responsive: true,
  657. plugins: {
  658. title: {
  659. display: true,
  660. text: '新客户产品类别销售占比'
  661. },
  662. tooltip: {
  663. callbacks: {
  664. label: function(context) {
  665. return context.label + ': ' + context.raw + '%';
  666. }
  667. }
  668. }
  669. }
  670. }
  671. });
  672. </script>
  673. <?php
  674. }