statistics_utils.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  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 htmlspecialchars($customer['company_name']); ?></td>
  265. <td><?php echo htmlspecialchars($customer['customer_code']); ?></td>
  266. <td><?php echo htmlspecialchars($customer['country']); ?></td>
  267. <td><?php echo htmlspecialchars($customer['customer_type'] ?: '未分类'); ?></td>
  268. <td><?php echo htmlspecialchars($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. <!-- 新增客户添加时间分布图 -->
  277. <div class="chart-container">
  278. <div>
  279. <canvas id="newCustomersChart"></canvas>
  280. </div>
  281. </div>
  282. <script>
  283. // 准备图表数据
  284. <?php
  285. // 按日期分组客户数量
  286. $dates = [];
  287. $counts = [];
  288. $dateGroups = [];
  289. foreach ($customers as $customer) {
  290. $date = date('Y-m-d', strtotime($customer['add_date']));
  291. if (!isset($dateGroups[$date])) {
  292. $dateGroups[$date] = 0;
  293. }
  294. $dateGroups[$date]++;
  295. }
  296. // 排序日期
  297. ksort($dateGroups);
  298. foreach ($dateGroups as $date => $count) {
  299. $dates[] = $date;
  300. $counts[] = $count;
  301. }
  302. ?>
  303. var newCustomersCtx = document.getElementById('newCustomersChart').getContext('2d');
  304. new Chart(newCustomersCtx, {
  305. type: 'bar',
  306. data: {
  307. labels: <?php echo json_encode($dates); ?>,
  308. datasets: [{
  309. label: '新增客户数量',
  310. data: <?php echo json_encode($counts); ?>,
  311. backgroundColor: 'rgba(54, 162, 235, 0.5)',
  312. borderColor: 'rgba(54, 162, 235, 1)',
  313. borderWidth: 1
  314. }]
  315. },
  316. options: {
  317. responsive: true,
  318. scales: {
  319. y: {
  320. beginAtZero: true,
  321. title: {
  322. display: true,
  323. text: '客户数量'
  324. }
  325. },
  326. x: {
  327. title: {
  328. display: true,
  329. text: '日期'
  330. }
  331. }
  332. },
  333. plugins: {
  334. title: {
  335. display: true,
  336. text: '新增客户时间分布'
  337. }
  338. }
  339. }
  340. });
  341. </script>
  342. <?php
  343. }
  344. /**
  345. * 渲染业务员新增客户图表
  346. *
  347. * @param array $employee_data 业务员新增客户数据
  348. * @return void
  349. */
  350. function renderNewCustomersByEmployeeChart($employee_data) {
  351. if (empty($employee_data)) {
  352. echo '<div class="alert alert-info">该时间段内没有业务员新增客户数据</div>';
  353. return;
  354. }
  355. // 准备图表数据
  356. $employee_names = [];
  357. $customer_counts = [];
  358. foreach ($employee_data as $row) {
  359. $employee_names[] = $row['employee_name'];
  360. $customer_counts[] = $row['customer_count'];
  361. }
  362. // 生成图表背景色
  363. $colors = generateChartColors(count($employee_data));
  364. $backgroundColors = [];
  365. $borderColors = [];
  366. foreach ($colors as $color) {
  367. $backgroundColors[] = $color[0];
  368. $borderColors[] = $color[1];
  369. }
  370. ?>
  371. <div class="analysis-grid">
  372. <div>
  373. <canvas id="employeeNewCustomersChart"></canvas>
  374. </div>
  375. <div class="table-responsive">
  376. <table class="data-table">
  377. <thead>
  378. <tr>
  379. <th>业务员</th>
  380. <th>新增客户数量</th>
  381. </tr>
  382. </thead>
  383. <tbody>
  384. <?php foreach ($employee_data as $row): ?>
  385. <tr>
  386. <td><?php echo htmlspecialchars($row['employee_name']); ?></td>
  387. <td><?php echo number_format($row['customer_count']); ?></td>
  388. </tr>
  389. <?php endforeach; ?>
  390. </tbody>
  391. </table>
  392. </div>
  393. </div>
  394. <script>
  395. var employeeNewCustomersCtx = document.getElementById('employeeNewCustomersChart').getContext('2d');
  396. new Chart(employeeNewCustomersCtx, {
  397. type: 'bar',
  398. data: {
  399. labels: <?php echo json_encode($employee_names); ?>,
  400. datasets: [{
  401. label: '新增客户数量',
  402. data: <?php echo json_encode($customer_counts); ?>,
  403. backgroundColor: <?php echo json_encode($backgroundColors); ?>,
  404. borderColor: <?php echo json_encode($borderColors); ?>,
  405. borderWidth: 1
  406. }]
  407. },
  408. options: {
  409. responsive: true,
  410. scales: {
  411. y: {
  412. beginAtZero: true,
  413. title: {
  414. display: true,
  415. text: '客户数量'
  416. }
  417. }
  418. },
  419. plugins: {
  420. title: {
  421. display: true,
  422. text: '业务员新增客户统计'
  423. }
  424. }
  425. }
  426. });
  427. </script>
  428. <?php
  429. }
  430. /**
  431. * 根据用户角色获取可见的业务员列表
  432. *
  433. * @param mysqli $conn 数据库连接
  434. * @param int $user_id 当前用户ID
  435. * @return array 可访问的业务员ID和姓名列表
  436. */
  437. function getAccessibleEmployees($conn, $user_id) {
  438. // 获取当前用户信息
  439. $sql = "SELECT em_user, em_role FROM employee WHERE id = ?";
  440. $stmt = $conn->prepare($sql);
  441. $stmt->bind_param("i", $user_id);
  442. $stmt->execute();
  443. $result = $stmt->get_result();
  444. $user = $result->fetch_assoc();
  445. $role = $user['em_role'] ?? 0;
  446. $employees = [];
  447. if ($role == 1) {
  448. // 管理员可以看到所有业务员
  449. $sql = "SELECT id, em_user FROM employee WHERE em_role IS NOT NULL ORDER BY em_user";
  450. $result = $conn->query($sql);
  451. while ($row = $result->fetch_assoc()) {
  452. $employees[] = [
  453. 'id' => $row['id'],
  454. 'name' => $row['em_user']
  455. ];
  456. }
  457. } else if ($role == 2) {
  458. // 获取组长自己和其团队成员
  459. $sql = "SELECT id, em_user FROM employee WHERE id = ? OR em_role = ? ORDER BY em_user";
  460. $stmt = $conn->prepare($sql);
  461. $stmt->bind_param("ii", $user_id, $user_id);
  462. $stmt->execute();
  463. $result = $stmt->get_result();
  464. while ($row = $result->fetch_assoc()) {
  465. $employees[] = [
  466. 'id' => $row['id'],
  467. 'name' => $row['em_user']
  468. ];
  469. }
  470. } else {
  471. // 普通业务员只能看到自己
  472. $sql = "SELECT id, em_user FROM employee WHERE id = ?";
  473. $stmt = $conn->prepare($sql);
  474. $stmt->bind_param("i", $user_id);
  475. $stmt->execute();
  476. $result = $stmt->get_result();
  477. while ($row = $result->fetch_assoc()) {
  478. $employees[] = [
  479. 'id' => $row['id'],
  480. 'name' => $row['em_user']
  481. ];
  482. }
  483. }
  484. return $employees;
  485. }
  486. /**
  487. * 根据用户角色获取默认的业务员筛选列表
  488. *
  489. * @param mysqli $conn 数据库连接
  490. * @param int $user_id 当前用户ID
  491. * @return array|int|null 业务员筛选值,可能是单个ID、ID数组或null
  492. */
  493. function getDefaultEmployeeFilter($conn, $user_id) {
  494. // 获取当前用户角色
  495. $sql = "SELECT em_role FROM employee WHERE id = ?";
  496. $stmt = $conn->prepare($sql);
  497. $stmt->bind_param("i", $user_id);
  498. $stmt->execute();
  499. $result = $stmt->get_result();
  500. $user = $result->fetch_assoc();
  501. $role = $user['em_role'] ?? 0;
  502. if ($role == 1) {
  503. // 管理员默认看所有人
  504. return null;
  505. } else if ($role == 2) {
  506. // 团队组长默认看他的团队
  507. $sql = "SELECT id FROM employee WHERE id = ? OR em_role = ?";
  508. $stmt = $conn->prepare($sql);
  509. $stmt->bind_param("ii", $user_id, $user_id);
  510. $stmt->execute();
  511. $result = $stmt->get_result();
  512. $emp_ids = [];
  513. while ($row = $result->fetch_assoc()) {
  514. $emp_ids[] = $row['id'];
  515. }
  516. return $emp_ids;
  517. } else {
  518. // 普通业务员只看自己
  519. return $user_id;
  520. }
  521. }
  522. /**
  523. * 渲染新客户产品购买明细
  524. *
  525. * @param array $product_data 产品购买数据
  526. * @return void
  527. */
  528. function renderNewCustomerProductPurchases($product_data) {
  529. if (empty($product_data) || empty($product_data['products'])) {
  530. echo '<div class="alert alert-info">该时间段内没有新客户购买产品数据</div>';
  531. return;
  532. }
  533. $products = $product_data['products'];
  534. $new_customer_count = $product_data['new_customer_count'];
  535. ?>
  536. <div class="section-intro">
  537. <p>本期间共有 <strong><?php echo number_format($new_customer_count); ?></strong> 名新客户进行了购买。以下是他们购买的产品明细:</p>
  538. </div>
  539. <div class="table-responsive">
  540. <table class="data-table">
  541. <thead>
  542. <tr>
  543. <th>产品名称</th>
  544. <th>产品分类</th>
  545. <th>订单数</th>
  546. <th>购买客户数</th>
  547. <th>销售数量</th>
  548. <th>销售金额</th>
  549. <th>平均单价</th>
  550. </tr>
  551. </thead>
  552. <tbody>
  553. <?php foreach ($products as $product): ?>
  554. <tr>
  555. <td><?php echo htmlspecialchars($product['product_name']); ?></td>
  556. <td><?php echo htmlspecialchars($product['category_name'] ?: '未分类'); ?></td>
  557. <td><?php echo number_format($product['order_count']); ?></td>
  558. <td><?php echo number_format($product['customer_count']); ?></td>
  559. <td><?php echo number_format($product['total_quantity']); ?></td>
  560. <td><?php echo formatCurrency($product['total_revenue']); ?></td>
  561. <td><?php echo formatCurrency($product['avg_price']); ?></td>
  562. </tr>
  563. <?php endforeach; ?>
  564. </tbody>
  565. </table>
  566. </div>
  567. <!-- 新客户产品购买分布图 -->
  568. <div class="chart-container">
  569. <div>
  570. <canvas id="newCustomerProductChart"></canvas>
  571. </div>
  572. </div>
  573. <script>
  574. <?php
  575. // 准备图表数据
  576. $product_names = [];
  577. $product_quantities = [];
  578. $product_revenues = [];
  579. // 只取前10个产品用于图表显示
  580. $top_products = array_slice($products, 0, 10);
  581. foreach ($top_products as $product) {
  582. $product_names[] = $product['product_name'];
  583. $product_quantities[] = $product['total_quantity'];
  584. $product_revenues[] = $product['total_revenue'];
  585. }
  586. // 生成图表背景色
  587. $colors = generateChartColors(count($top_products));
  588. $backgroundColors = [];
  589. foreach ($colors as $color) {
  590. $backgroundColors[] = $color[0];
  591. }
  592. ?>
  593. var newCustomerProductCtx = document.getElementById('newCustomerProductChart').getContext('2d');
  594. new Chart(newCustomerProductCtx, {
  595. type: 'bar',
  596. data: {
  597. labels: <?php echo json_encode($product_names); ?>,
  598. datasets: [
  599. {
  600. label: '销售数量',
  601. data: <?php echo json_encode($product_quantities); ?>,
  602. backgroundColor: 'rgba(54, 162, 235, 0.7)',
  603. borderColor: 'rgba(54, 162, 235, 1)',
  604. borderWidth: 1,
  605. yAxisID: 'y-quantity'
  606. },
  607. {
  608. label: '销售金额',
  609. data: <?php echo json_encode($product_revenues); ?>,
  610. backgroundColor: 'rgba(255, 99, 132, 0.7)',
  611. borderColor: 'rgba(255, 99, 132, 1)',
  612. borderWidth: 1,
  613. yAxisID: 'y-revenue',
  614. type: 'line',
  615. fill: false
  616. }
  617. ]
  618. },
  619. options: {
  620. responsive: true,
  621. scales: {
  622. 'y-quantity': {
  623. type: 'linear',
  624. position: 'left',
  625. title: {
  626. display: true,
  627. text: '销售数量'
  628. },
  629. beginAtZero: true
  630. },
  631. 'y-revenue': {
  632. type: 'linear',
  633. position: 'right',
  634. title: {
  635. display: true,
  636. text: '销售金额'
  637. },
  638. beginAtZero: true,
  639. grid: {
  640. drawOnChartArea: false
  641. }
  642. }
  643. },
  644. plugins: {
  645. title: {
  646. display: true,
  647. text: '新客户热门购买产品 (Top 10)'
  648. }
  649. }
  650. }
  651. });
  652. </script>
  653. <!-- 新客户产品类别分布图 -->
  654. <div class="chart-container">
  655. <div>
  656. <canvas id="newCustomerCategoryChart"></canvas>
  657. </div>
  658. </div>
  659. <script>
  660. <?php
  661. // 按产品类别分组
  662. $categories = [];
  663. $category_data = [];
  664. foreach ($products as $product) {
  665. $category = $product['category_name'] ?: '未分类';
  666. if (!isset($category_data[$category])) {
  667. $category_data[$category] = [
  668. 'quantity' => 0,
  669. 'revenue' => 0
  670. ];
  671. }
  672. $category_data[$category]['quantity'] += $product['total_quantity'];
  673. $category_data[$category]['revenue'] += $product['total_revenue'];
  674. }
  675. $category_names = array_keys($category_data);
  676. $category_quantities = array_column($category_data, 'quantity');
  677. $category_revenues = array_column($category_data, 'revenue');
  678. // 计算占比
  679. $total_revenue = array_sum($category_revenues);
  680. $revenue_percentages = [];
  681. foreach ($category_revenues as $revenue) {
  682. $revenue_percentages[] = round(($revenue / $total_revenue) * 100, 1);
  683. }
  684. // 生成图表背景色
  685. $category_colors = generateChartColors(count($category_data), false);
  686. $category_bg_colors = array_column($category_colors, 0);
  687. ?>
  688. var newCustomerCategoryCtx = document.getElementById('newCustomerCategoryChart').getContext('2d');
  689. new Chart(newCustomerCategoryCtx, {
  690. type: 'pie',
  691. data: {
  692. labels: <?php echo json_encode($category_names); ?>,
  693. datasets: [{
  694. data: <?php echo json_encode($revenue_percentages); ?>,
  695. backgroundColor: <?php echo json_encode($category_bg_colors); ?>,
  696. borderWidth: 1
  697. }]
  698. },
  699. options: {
  700. responsive: true,
  701. plugins: {
  702. title: {
  703. display: true,
  704. text: '新客户产品类别销售占比'
  705. },
  706. tooltip: {
  707. callbacks: {
  708. label: function(context) {
  709. return context.label + ': ' + context.raw + '%';
  710. }
  711. }
  712. }
  713. }
  714. }
  715. });
  716. </script>
  717. <?php
  718. }