statistics_products.php 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416
  1. <?php
  2. /**
  3. * 产品统计分析模块
  4. *
  5. * 包含与产品相关的数据分析功能
  6. */
  7. require_once 'statistics_utils.php';
  8. /**
  9. * 获取热门产品数据
  10. *
  11. * @param mysqli $conn 数据库连接
  12. * @param string $start_date 开始日期
  13. * @param string $end_date 结束日期
  14. * @param int $limit 限制返回的产品数量
  15. * @param mixed $employee_filter 业务员过滤条件
  16. * @return mysqli_result 热门产品数据结果集
  17. */
  18. function getTopProducts($conn, $start_date, $end_date, $limit = 5, $employee_filter = null) {
  19. $sql = "SELECT
  20. p.ProductName,
  21. SUM(oi.quantity) as total_quantity,
  22. SUM(oi.total_price) as total_revenue
  23. FROM order_items oi
  24. JOIN products p ON oi.product_id = p.id
  25. JOIN orders o ON oi.order_id = o.id";
  26. if ($employee_filter !== null) {
  27. $sql .= " JOIN customer c ON o.customer_id = c.id";
  28. }
  29. $sql .= " WHERE o.is_deleted = 0 AND oi.is_deleted = 0 AND o.order_date BETWEEN '$start_date' AND '$end_date'";
  30. // 添加业务员过滤
  31. if ($employee_filter !== null) {
  32. if (is_array($employee_filter)) {
  33. if (count($employee_filter) > 0) {
  34. $employee_ids = implode(',', $employee_filter);
  35. $sql .= " AND c.cs_belong IN ($employee_ids)";
  36. }
  37. } else {
  38. $sql .= " AND c.cs_belong = $employee_filter";
  39. }
  40. }
  41. $sql .= " GROUP BY oi.product_id
  42. ORDER BY total_revenue DESC
  43. LIMIT $limit";
  44. $result = $conn->query($sql);
  45. return $result;
  46. }
  47. /**
  48. * 获取产品销售趋势
  49. *
  50. * @param mysqli $conn 数据库连接
  51. * @param string $start_date 开始日期
  52. * @param string $end_date 结束日期
  53. * @param int $product_id 产品ID,为0时获取所有产品的总体趋势
  54. * @param string $period 时间粒度 (day/week/month)
  55. * @param mixed $employee_filter 业务员过滤条件
  56. * @return mysqli_result 产品销售趋势数据结果集
  57. */
  58. function getProductSalesTrend($conn, $start_date, $end_date, $product_id = 0, $period = 'month', $employee_filter = null) {
  59. $groupFormat = '%Y-%m-%d';
  60. if ($period == 'week') {
  61. $groupFormat = '%x-W%v'; // ISO year and week number
  62. } else if ($period == 'month') {
  63. $groupFormat = '%Y-%m';
  64. }
  65. $sql = "SELECT
  66. DATE_FORMAT(o.order_date, '$groupFormat') as time_period,
  67. SUM(oi.quantity) as total_quantity,
  68. SUM(oi.total_price) as total_revenue,
  69. COUNT(DISTINCT o.id) as order_count
  70. FROM order_items oi
  71. JOIN orders o ON oi.order_id = o.id";
  72. if ($employee_filter !== null) {
  73. $sql .= " JOIN customer c ON o.customer_id = c.id";
  74. }
  75. $sql .= " WHERE o.is_deleted = 0 AND oi.is_deleted = 0 AND o.order_date BETWEEN '$start_date' AND '$end_date'";
  76. if ($product_id > 0) {
  77. $sql .= " AND oi.product_id = $product_id";
  78. }
  79. // 添加业务员过滤
  80. if ($employee_filter !== null) {
  81. if (is_array($employee_filter)) {
  82. if (count($employee_filter) > 0) {
  83. $employee_ids = implode(',', $employee_filter);
  84. $sql .= " AND c.cs_belong IN ($employee_ids)";
  85. }
  86. } else {
  87. $sql .= " AND c.cs_belong = $employee_filter";
  88. }
  89. }
  90. $sql .= " GROUP BY time_period
  91. ORDER BY MIN(o.order_date)";
  92. $result = $conn->query($sql);
  93. return $result;
  94. }
  95. /**
  96. * 获取产品类别销售分布
  97. *
  98. * @param mysqli $conn 数据库连接
  99. * @param string $start_date 开始日期
  100. * @param string $end_date 结束日期
  101. * @param mixed $employee_filter 业务员过滤条件
  102. * @return mysqli_result 产品类别销售分布数据结果集
  103. */
  104. function getProductCategorySales($conn, $start_date, $end_date, $employee_filter = null) {
  105. $sql = "SELECT
  106. pc.name as category_name,
  107. SUM(oi.quantity) as total_quantity,
  108. SUM(oi.total_price) as total_revenue,
  109. COUNT(DISTINCT o.id) as order_count
  110. FROM order_items oi
  111. JOIN products p ON oi.product_id = p.id
  112. JOIN product_categories pc ON p.category_id = pc.id
  113. JOIN orders o ON oi.order_id = o.id";
  114. if ($employee_filter !== null) {
  115. $sql .= " JOIN customer c ON o.customer_id = c.id";
  116. }
  117. $sql .= " WHERE o.is_deleted = 0 AND oi.is_deleted = 0 AND o.order_date BETWEEN '$start_date' AND '$end_date'";
  118. // 添加业务员过滤
  119. if ($employee_filter !== null) {
  120. if (is_array($employee_filter)) {
  121. if (count($employee_filter) > 0) {
  122. $employee_ids = implode(',', $employee_filter);
  123. $sql .= " AND c.cs_belong IN ($employee_ids)";
  124. }
  125. } else {
  126. $sql .= " AND c.cs_belong = $employee_filter";
  127. }
  128. }
  129. $sql .= " GROUP BY p.category_id
  130. ORDER BY total_revenue DESC";
  131. $result = $conn->query($sql);
  132. return $result;
  133. }
  134. /**
  135. * 获取产品与地区关联分析
  136. *
  137. * @param mysqli $conn 数据库连接
  138. * @param string $start_date 开始日期
  139. * @param string $end_date 结束日期
  140. * @param mixed $employee_filter 业务员过滤条件
  141. * @param int $limit 限制返回的产品-地区组合数量
  142. * @return mysqli_result 产品与地区关联分析数据结果集
  143. */
  144. function getProductRegionAnalysis($conn, $start_date, $end_date, $employee_filter = null, $limit = 10) {
  145. $sql = "SELECT
  146. p.ProductName,
  147. c.countryName,
  148. SUM(oi.quantity) as total_quantity,
  149. SUM(oi.total_price) as total_revenue
  150. FROM order_items oi
  151. JOIN products p ON oi.product_id = p.id
  152. JOIN orders o ON oi.order_id = o.id
  153. JOIN customer cu ON o.customer_id = cu.id
  154. JOIN country c ON cu.cs_country = c.id";
  155. $sql .= " WHERE o.is_deleted = 0 AND oi.is_deleted = 0 AND o.order_date BETWEEN '$start_date' AND '$end_date'";
  156. // 添加业务员过滤
  157. if ($employee_filter !== null) {
  158. if (is_array($employee_filter)) {
  159. if (count($employee_filter) > 0) {
  160. $employee_ids = implode(',', $employee_filter);
  161. $sql .= " AND cu.cs_belong IN ($employee_ids)";
  162. }
  163. } else {
  164. $sql .= " AND cu.cs_belong = $employee_filter";
  165. }
  166. }
  167. $sql .= " GROUP BY oi.product_id, cu.cs_country
  168. ORDER BY total_revenue DESC
  169. LIMIT $limit";
  170. $result = $conn->query($sql);
  171. return $result;
  172. }
  173. /**
  174. * 获取产品销售概览数据
  175. *
  176. * @param mysqli $conn 数据库连接
  177. * @param string $start_date 开始日期
  178. * @param string $end_date 结束日期
  179. * @param int $category_filter 产品分类过滤
  180. * @param mixed $employee_filter 业务员过滤条件
  181. * @return array 产品销售概览数据
  182. */
  183. function getProductSalesOverview($conn, $start_date, $end_date, $category_filter = 0, $employee_filter = null) {
  184. $where_clause = "WHERE o.is_deleted = 0 AND oi.is_deleted = 0 AND o.order_date BETWEEN '$start_date' AND '$end_date'";
  185. if ($category_filter > 0) {
  186. $where_clause .= " AND p.category_id = $category_filter";
  187. }
  188. $sql = "SELECT
  189. COUNT(DISTINCT oi.product_id) as total_products,
  190. SUM(oi.quantity) as total_quantity,
  191. SUM(oi.total_price) as total_revenue,
  192. AVG(oi.unit_price) as avg_unit_price,
  193. COUNT(DISTINCT o.id) as total_orders,
  194. SUM(oi.total_price) / COUNT(DISTINCT o.id) as avg_order_value,
  195. COUNT(DISTINCT o.customer_id) as total_customers
  196. FROM order_items oi
  197. JOIN orders o ON oi.order_id = o.id
  198. JOIN products p ON oi.product_id = p.id";
  199. if ($employee_filter !== null) {
  200. $sql .= " JOIN customer c ON o.customer_id = c.id";
  201. }
  202. $sql .= " $where_clause";
  203. // 添加业务员过滤
  204. if ($employee_filter !== null) {
  205. if (is_array($employee_filter)) {
  206. if (count($employee_filter) > 0) {
  207. $employee_ids = implode(',', $employee_filter);
  208. $sql .= " AND c.cs_belong IN ($employee_ids)";
  209. }
  210. } else {
  211. $sql .= " AND c.cs_belong = $employee_filter";
  212. }
  213. }
  214. $result = $conn->query($sql);
  215. return $result->fetch_assoc();
  216. }
  217. /**
  218. * 获取产品价格趋势分析
  219. *
  220. * @param mysqli $conn 数据库连接
  221. * @param string $start_date 开始日期
  222. * @param string $end_date 结束日期
  223. * @param int $product_id 产品ID
  224. * @param string $period 时间粒度
  225. * @param mixed $employee_filter 业务员过滤条件
  226. * @return mysqli_result 产品价格趋势数据
  227. */
  228. function getProductPriceTrendAnalysis($conn, $start_date, $end_date, $product_id = 0, $period = 'month', $employee_filter = null) {
  229. $groupFormat = getPeriodFormat($period);
  230. $sql = "SELECT
  231. DATE_FORMAT(o.order_date, '$groupFormat') as time_period,
  232. AVG(oi.unit_price) as avg_price,
  233. MIN(oi.unit_price) as min_price,
  234. MAX(oi.unit_price) as max_price
  235. FROM order_items oi
  236. JOIN orders o ON oi.order_id = o.id";
  237. if ($employee_filter !== null) {
  238. $sql .= " JOIN customer c ON o.customer_id = c.id";
  239. }
  240. $sql .= " WHERE o.is_deleted = 0 AND oi.is_deleted = 0 AND o.order_date BETWEEN '$start_date' AND '$end_date'";
  241. if ($product_id > 0) {
  242. $sql .= " AND oi.product_id = $product_id";
  243. }
  244. // 添加业务员过滤
  245. if ($employee_filter !== null) {
  246. if (is_array($employee_filter)) {
  247. if (count($employee_filter) > 0) {
  248. $employee_ids = implode(',', $employee_filter);
  249. $sql .= " AND c.cs_belong IN ($employee_ids)";
  250. }
  251. } else {
  252. $sql .= " AND c.cs_belong = $employee_filter";
  253. }
  254. }
  255. $sql .= " GROUP BY time_period ORDER BY MIN(o.order_date)";
  256. $result = $conn->query($sql);
  257. return $result;
  258. }
  259. /**
  260. * 获取产品季节性分析
  261. *
  262. * @param mysqli $conn 数据库连接
  263. * @param string $start_date 开始日期
  264. * @param string $end_date 结束日期
  265. * @param int $product_id 产品ID
  266. * @param mixed $employee_filter 业务员过滤条件
  267. * @return mysqli_result 产品季节性分析数据
  268. */
  269. function getProductSeasonalityAnalysis($conn, $start_date, $end_date, $product_id = 0, $employee_filter = null) {
  270. $sql = "SELECT
  271. MONTH(o.order_date) as month,
  272. SUM(oi.quantity) as total_quantity,
  273. SUM(oi.total_price) as total_revenue,
  274. COUNT(DISTINCT o.id) as order_count
  275. FROM order_items oi
  276. JOIN orders o ON oi.order_id = o.id";
  277. if ($employee_filter !== null) {
  278. $sql .= " JOIN customer c ON o.customer_id = c.id";
  279. }
  280. $sql .= " WHERE o.is_deleted = 0 AND oi.is_deleted = 0 AND o.order_date BETWEEN '$start_date' AND '$end_date'";
  281. if ($product_id > 0) {
  282. $sql .= " AND oi.product_id = $product_id";
  283. }
  284. // 添加业务员过滤
  285. if ($employee_filter !== null) {
  286. if (is_array($employee_filter)) {
  287. if (count($employee_filter) > 0) {
  288. $employee_ids = implode(',', $employee_filter);
  289. $sql .= " AND c.cs_belong IN ($employee_ids)";
  290. }
  291. } else {
  292. $sql .= " AND c.cs_belong = $employee_filter";
  293. }
  294. }
  295. $sql .= " GROUP BY MONTH(o.order_date)
  296. ORDER BY MONTH(o.order_date)";
  297. $result = $conn->query($sql);
  298. return $result;
  299. }
  300. /**
  301. * 获取产品客户细分分析
  302. *
  303. * @param mysqli $conn 数据库连接
  304. * @param string $start_date 开始日期
  305. * @param string $end_date 结束日期
  306. * @param int $product_id 产品ID
  307. * @param mixed $employee_filter 业务员过滤条件
  308. * @return mysqli_result 产品客户细分分析数据
  309. */
  310. function getProductCustomerSegmentAnalysis($conn, $start_date, $end_date, $product_id = 0, $employee_filter = null) {
  311. $sql = "SELECT
  312. ct.businessType as segment_name,
  313. COUNT(DISTINCT o.customer_id) as customer_count,
  314. SUM(oi.quantity) as total_quantity,
  315. SUM(oi.total_price) as total_revenue,
  316. AVG(oi.unit_price) as avg_unit_price
  317. FROM order_items oi
  318. JOIN orders o ON oi.order_id = o.id
  319. JOIN customer c ON o.customer_id = c.id
  320. JOIN clienttype ct ON c.cs_type = ct.id";
  321. $sql .= " WHERE o.is_deleted = 0 AND oi.is_deleted = 0 AND o.order_date BETWEEN '$start_date' AND '$end_date'";
  322. if ($product_id > 0) {
  323. $sql .= " AND oi.product_id = $product_id";
  324. }
  325. // 添加业务员过滤
  326. if ($employee_filter !== null) {
  327. if (is_array($employee_filter)) {
  328. if (count($employee_filter) > 0) {
  329. $employee_ids = implode(',', $employee_filter);
  330. $sql .= " AND c.cs_belong IN ($employee_ids)";
  331. }
  332. } else {
  333. $sql .= " AND c.cs_belong = $employee_filter";
  334. }
  335. }
  336. $sql .= " GROUP BY ct.id";
  337. $result = $conn->query($sql);
  338. return $result;
  339. }
  340. /**
  341. * 获取产品分类列表
  342. *
  343. * @param mysqli $conn 数据库连接
  344. * @return mysqli_result 产品分类数据结果集
  345. */
  346. function getProductCategories($conn) {
  347. $sql = "SELECT
  348. id,
  349. parent_id,
  350. name,
  351. description,
  352. sort_order
  353. FROM product_categories
  354. WHERE status = 1
  355. ORDER BY sort_order ASC, id ASC";
  356. $stmt = $conn->prepare($sql);
  357. $stmt->execute();
  358. return $stmt->get_result();
  359. }
  360. /**
  361. * 渲染热门产品表格
  362. *
  363. * @param mysqli_result $top_products 热门产品数据
  364. * @return void
  365. */
  366. function renderTopProductsTable($top_products) {
  367. ?>
  368. <div class="chart-container" style="padding-left:0px;padding-right: 0px;">
  369. <div class="chart-header">
  370. <h2 class="chart-title">热门产品 TOP 10</h2>
  371. </div>
  372. <table class="data-table">
  373. <thead>
  374. <tr>
  375. <th>产品名称</th>
  376. <th>销售数量</th>
  377. <th>销售收入</th>
  378. </tr>
  379. </thead>
  380. <tbody>
  381. <?php while ($row = $top_products->fetch_assoc()): ?>
  382. <tr>
  383. <td><?php echo htmlspecialchars($row['ProductName']); ?></td>
  384. <td><?php echo number_format($row['total_quantity']); ?></td>
  385. <td>¥<?php echo number_format($row['total_revenue'], 2); ?></td>
  386. </tr>
  387. <?php endwhile; ?>
  388. </tbody>
  389. </table>
  390. </div>
  391. <?php
  392. }
  393. /**
  394. * 渲染产品销售趋势图
  395. *
  396. * @param array $time_labels 时间标签
  397. * @param array $quantities 产品销售数量
  398. * @param array $revenues 产品销售收入
  399. * @return void
  400. */
  401. function renderProductSalesTrendChart($time_labels, $quantities, $revenues) {
  402. ?>
  403. <div class="chart-container">
  404. <div class="chart-header">
  405. <h2 class="chart-title">产品销售趋势</h2>
  406. </div>
  407. <canvas id="productSalesTrendChart"></canvas>
  408. </div>
  409. <script>
  410. // 产品销售趋势图
  411. var productSalesTrendCtx = document.getElementById('productSalesTrendChart').getContext('2d');
  412. var productSalesTrendChart = new Chart(productSalesTrendCtx, {
  413. type: 'line',
  414. data: {
  415. labels: <?php echo json_encode($time_labels); ?>,
  416. datasets: [
  417. {
  418. label: '销售数量',
  419. data: <?php echo json_encode($quantities); ?>,
  420. backgroundColor: 'rgba(54, 162, 235, 0.2)',
  421. borderColor: 'rgba(54, 162, 235, 1)',
  422. borderWidth: 2,
  423. yAxisID: 'y-quantity',
  424. tension: 0.1
  425. },
  426. {
  427. label: '销售收入',
  428. data: <?php echo json_encode($revenues); ?>,
  429. backgroundColor: 'rgba(255, 99, 132, 0.2)',
  430. borderColor: 'rgba(255, 99, 132, 1)',
  431. borderWidth: 2,
  432. yAxisID: 'y-revenue',
  433. tension: 0.1
  434. }
  435. ]
  436. },
  437. options: {
  438. responsive: true,
  439. scales: {
  440. 'y-quantity': {
  441. type: 'linear',
  442. position: 'left',
  443. title: {
  444. display: true,
  445. text: '销售数量'
  446. },
  447. beginAtZero: true
  448. },
  449. 'y-revenue': {
  450. type: 'linear',
  451. position: 'right',
  452. title: {
  453. display: true,
  454. text: '销售收入'
  455. },
  456. beginAtZero: true,
  457. grid: {
  458. drawOnChartArea: false
  459. }
  460. }
  461. }
  462. }
  463. });
  464. </script>
  465. <?php
  466. }
  467. /**
  468. * 渲染产品类别销售分布图
  469. *
  470. * @param array $categories 类别名称
  471. * @param array $quantities 类别销售数量
  472. * @param array $revenues 类别销售收入
  473. * @return void
  474. */
  475. function renderProductCategorySalesChart($categories, $quantities, $revenues) {
  476. ?>
  477. <div class="chart-container">
  478. <div class="chart-header">
  479. <h2 class="chart-title">产品类别销售分布</h2>
  480. </div>
  481. <style>
  482. .pie-charts-container {
  483. display: flex;
  484. flex-direction: row;
  485. justify-content: space-between;
  486. margin-bottom: 20px;
  487. }
  488. .pie-chart-wrapper {
  489. flex: 0 0 48%;
  490. max-width: 48%;
  491. }
  492. </style>
  493. <div class="pie-charts-container">
  494. <div class="pie-chart-wrapper">
  495. <h3 style="text-align: center; margin-bottom: 15px;">产品类别销售数量分布</h3>
  496. <canvas id="categoryQuantityChart"></canvas>
  497. </div>
  498. <div class="pie-chart-wrapper">
  499. <h3 style="text-align: center; margin-bottom: 15px;">产品类别销售收入分布</h3>
  500. <canvas id="categoryRevenueChart"></canvas>
  501. </div>
  502. </div>
  503. </div>
  504. <script>
  505. // 产品类别数量分布图
  506. var categoryQuantityCtx = document.getElementById('categoryQuantityChart').getContext('2d');
  507. var categoryQuantityChart = new Chart(categoryQuantityCtx, {
  508. type: 'pie',
  509. data: {
  510. labels: <?php echo json_encode($categories); ?>,
  511. datasets: [{
  512. data: <?php echo json_encode($quantities); ?>,
  513. backgroundColor: [
  514. 'rgba(255, 99, 132, 0.7)',
  515. 'rgba(54, 162, 235, 0.7)',
  516. 'rgba(255, 206, 86, 0.7)',
  517. 'rgba(75, 192, 192, 0.7)',
  518. 'rgba(153, 102, 255, 0.7)',
  519. 'rgba(255, 159, 64, 0.7)'
  520. ],
  521. borderWidth: 1
  522. }]
  523. },
  524. options: {
  525. responsive: true,
  526. maintainAspectRatio: true,
  527. plugins: {
  528. legend: {
  529. position: 'bottom',
  530. }
  531. }
  532. }
  533. });
  534. // 产品类别收入分布图
  535. var categoryRevenueCtx = document.getElementById('categoryRevenueChart').getContext('2d');
  536. var categoryRevenueChart = new Chart(categoryRevenueCtx, {
  537. type: 'pie',
  538. data: {
  539. labels: <?php echo json_encode($categories); ?>,
  540. datasets: [{
  541. data: <?php echo json_encode($revenues); ?>,
  542. backgroundColor: [
  543. 'rgba(255, 99, 132, 0.7)',
  544. 'rgba(54, 162, 235, 0.7)',
  545. 'rgba(255, 206, 86, 0.7)',
  546. 'rgba(75, 192, 192, 0.7)',
  547. 'rgba(153, 102, 255, 0.7)',
  548. 'rgba(255, 159, 64, 0.7)'
  549. ],
  550. borderWidth: 1
  551. }]
  552. },
  553. options: {
  554. responsive: true,
  555. maintainAspectRatio: true,
  556. plugins: {
  557. legend: {
  558. position: 'bottom',
  559. }
  560. }
  561. }
  562. });
  563. </script>
  564. <?php
  565. }
  566. /**
  567. * 渲染产品与地区关联分析表格
  568. *
  569. * @param mysqli_result $product_region_data 产品与地区关联数据
  570. * @return void
  571. */
  572. function renderProductRegionAnalysisTable($product_region_data) {
  573. ?>
  574. <div class="chart-container">
  575. <div class="chart-header">
  576. <h2 class="chart-title">产品地区关联分析</h2>
  577. </div>
  578. <table class="data-table">
  579. <thead>
  580. <tr>
  581. <th>产品名称</th>
  582. <th>国家/地区</th>
  583. <th>销售数量</th>
  584. <th>销售收入</th>
  585. </tr>
  586. </thead>
  587. <tbody>
  588. <?php while ($row = $product_region_data->fetch_assoc()): ?>
  589. <tr>
  590. <td><?php echo htmlspecialchars($row['ProductName']); ?></td>
  591. <td><?php echo htmlspecialchars($row['countryName']); ?></td>
  592. <td><?php echo number_format($row['total_quantity']); ?></td>
  593. <td>¥<?php echo number_format($row['total_revenue'], 2); ?></td>
  594. </tr>
  595. <?php endwhile; ?>
  596. </tbody>
  597. </table>
  598. </div>
  599. <?php
  600. }
  601. /**
  602. * 渲染产品销售概览
  603. */
  604. function renderProductSalesOverview($overview) {
  605. // 处理可能为null的值
  606. $total_products = isset($overview['total_products']) ? $overview['total_products'] : 0;
  607. $total_quantity = isset($overview['total_quantity']) ? $overview['total_quantity'] : 0;
  608. $total_revenue = isset($overview['total_revenue']) ? $overview['total_revenue'] : 0;
  609. $avg_unit_price = isset($overview['avg_unit_price']) ? $overview['avg_unit_price'] : 0;
  610. $total_orders = isset($overview['total_orders']) ? $overview['total_orders'] : 0;
  611. $avg_order_value = isset($overview['avg_order_value']) ? $overview['avg_order_value'] : 0;
  612. ?>
  613. <div class="stats-card-container">
  614. <div class="stats-card">
  615. <div class="stats-card-header">
  616. <h3>总销售产品数</h3>
  617. </div>
  618. <div class="stats-card-body">
  619. <div class="stats-card-value"><?php echo number_format($total_products); ?></div>
  620. <div class="stats-card-subtitle">种类</div>
  621. </div>
  622. </div>
  623. <div class="stats-card">
  624. <div class="stats-card-header">
  625. <h3>总销售数量</h3>
  626. </div>
  627. <div class="stats-card-body">
  628. <div class="stats-card-value"><?php echo number_format($total_quantity); ?></div>
  629. <div class="stats-card-subtitle">件</div>
  630. </div>
  631. </div>
  632. <div class="stats-card">
  633. <div class="stats-card-header">
  634. <h3>总销售收入</h3>
  635. </div>
  636. <div class="stats-card-body">
  637. <div class="stats-card-value">¥<?php echo number_format($total_revenue, 2); ?></div>
  638. <div class="stats-card-subtitle">元</div>
  639. </div>
  640. </div>
  641. <div class="stats-card">
  642. <div class="stats-card-header">
  643. <h3>平均单价</h3>
  644. </div>
  645. <div class="stats-card-body">
  646. <div class="stats-card-value">¥<?php echo number_format($avg_unit_price, 2); ?></div>
  647. <div class="stats-card-subtitle">元/件</div>
  648. </div>
  649. </div>
  650. <div class="stats-card">
  651. <div class="stats-card-header">
  652. <h3>订单数量</h3>
  653. </div>
  654. <div class="stats-card-body">
  655. <div class="stats-card-value"><?php echo number_format($total_orders); ?></div>
  656. <div class="stats-card-subtitle">笔</div>
  657. </div>
  658. </div>
  659. <div class="stats-card">
  660. <div class="stats-card-header">
  661. <h3>平均订单金额</h3>
  662. </div>
  663. <div class="stats-card-body">
  664. <div class="stats-card-value">¥<?php echo number_format($avg_order_value, 2); ?></div>
  665. <div class="stats-card-subtitle">元/订单</div>
  666. </div>
  667. </div>
  668. </div>
  669. <?php
  670. }
  671. /**
  672. * 渲染产品价格趋势图表
  673. */
  674. function renderProductPriceTrendChart($price_trend_data) {
  675. $time_periods = [];
  676. $avg_prices = [];
  677. $min_prices = [];
  678. $max_prices = [];
  679. while ($row = $price_trend_data->fetch_assoc()) {
  680. $time_periods[] = $row['time_period'];
  681. $avg_prices[] = round($row['avg_price'], 2);
  682. $min_prices[] = round($row['min_price'], 2);
  683. $max_prices[] = round($row['max_price'], 2);
  684. }
  685. ?>
  686. <div class="chart-container">
  687. <div class="chart-header">
  688. <h2 class="chart-title">产品价格趋势分析</h2>
  689. </div>
  690. <canvas id="priceTrendChart"></canvas>
  691. </div>
  692. <script>
  693. var priceTrendCtx = document.getElementById('priceTrendChart').getContext('2d');
  694. new Chart(priceTrendCtx, {
  695. type: 'line',
  696. data: {
  697. labels: <?php echo json_encode($time_periods); ?>,
  698. datasets: [
  699. {
  700. label: '平均价格',
  701. data: <?php echo json_encode($avg_prices); ?>,
  702. borderColor: 'rgb(54, 162, 235)',
  703. backgroundColor: 'rgba(54, 162, 235, 0.1)',
  704. borderWidth: 2,
  705. fill: false
  706. },
  707. {
  708. label: '最低价格',
  709. data: <?php echo json_encode($min_prices); ?>,
  710. borderColor: 'rgb(75, 192, 192)',
  711. backgroundColor: 'rgba(75, 192, 192, 0.1)',
  712. borderWidth: 2,
  713. fill: false
  714. },
  715. {
  716. label: '最高价格',
  717. data: <?php echo json_encode($max_prices); ?>,
  718. borderColor: 'rgb(255, 99, 132)',
  719. backgroundColor: 'rgba(255, 99, 132, 0.1)',
  720. borderWidth: 2,
  721. fill: false
  722. }
  723. ]
  724. },
  725. options: {
  726. responsive: true,
  727. scales: {
  728. y: {
  729. beginAtZero: true,
  730. title: {
  731. display: true,
  732. text: '价格 (元)'
  733. }
  734. }
  735. },
  736. plugins: {
  737. title: {
  738. display: true,
  739. text: '产品价格变化趋势'
  740. }
  741. }
  742. }
  743. });
  744. </script>
  745. <?php
  746. }
  747. /**
  748. * 渲染产品季节性分析图表
  749. */
  750. function renderProductSeasonalityChart($seasonality_data) {
  751. $months = [];
  752. $quantities = [];
  753. $revenues = [];
  754. $order_counts = [];
  755. while ($row = $seasonality_data->fetch_assoc()) {
  756. $months[] = date('n月', mktime(0, 0, 0, $row['month'], 1));
  757. $quantities[] = (int)$row['total_quantity'];
  758. $revenues[] = round($row['total_revenue'], 2);
  759. $order_counts[] = (int)$row['order_count'];
  760. }
  761. ?>
  762. <div class="chart-container">
  763. <div class="chart-header">
  764. <h2 class="chart-title">产品季节性分析</h2>
  765. </div>
  766. <canvas id="seasonalityChart"></canvas>
  767. </div>
  768. <script>
  769. var seasonalityCtx = document.getElementById('seasonalityChart').getContext('2d');
  770. new Chart(seasonalityCtx, {
  771. type: 'bar',
  772. data: {
  773. labels: <?php echo json_encode($months); ?>,
  774. datasets: [
  775. {
  776. label: '销售数量',
  777. data: <?php echo json_encode($quantities); ?>,
  778. backgroundColor: 'rgba(54, 162, 235, 0.5)',
  779. borderColor: 'rgb(54, 162, 235)',
  780. borderWidth: 1,
  781. yAxisID: 'y-quantity'
  782. },
  783. {
  784. label: '销售收入',
  785. data: <?php echo json_encode($revenues); ?>,
  786. backgroundColor: 'rgba(255, 99, 132, 0.5)',
  787. borderColor: 'rgb(255, 99, 132)',
  788. borderWidth: 1,
  789. yAxisID: 'y-revenue'
  790. },
  791. {
  792. label: '订单数',
  793. data: <?php echo json_encode($order_counts); ?>,
  794. type: 'line',
  795. fill: false,
  796. borderColor: 'rgb(75, 192, 192)',
  797. tension: 0.1,
  798. yAxisID: 'y-orders'
  799. }
  800. ]
  801. },
  802. options: {
  803. responsive: true,
  804. scales: {
  805. 'y-quantity': {
  806. type: 'linear',
  807. position: 'left',
  808. title: {
  809. display: true,
  810. text: '销售数量'
  811. }
  812. },
  813. 'y-revenue': {
  814. type: 'linear',
  815. position: 'right',
  816. title: {
  817. display: true,
  818. text: '销售收入 (元)'
  819. },
  820. grid: {
  821. drawOnChartArea: false
  822. }
  823. },
  824. 'y-orders': {
  825. type: 'linear',
  826. position: 'right',
  827. title: {
  828. display: true,
  829. text: '订单数'
  830. },
  831. grid: {
  832. drawOnChartArea: false
  833. }
  834. }
  835. },
  836. plugins: {
  837. title: {
  838. display: true,
  839. text: '产品销售季节性分布'
  840. }
  841. }
  842. }
  843. });
  844. </script>
  845. <?php
  846. }
  847. /**
  848. * 渲染产品客户细分分析图表
  849. */
  850. function renderProductCustomerSegmentChart($segment_data) {
  851. $segments = [];
  852. $customer_counts = [];
  853. $revenues = [];
  854. $avg_prices = [];
  855. while ($row = $segment_data->fetch_assoc()) {
  856. $segments[] = $row['segment_name'];
  857. $customer_counts[] = (int)$row['customer_count'];
  858. $revenues[] = round($row['total_revenue'], 2);
  859. $avg_prices[] = round($row['avg_unit_price'], 2);
  860. }
  861. ?>
  862. <div class="chart-container">
  863. <div class="chart-header">
  864. <h2 class="chart-title">产品客户细分分析</h2>
  865. </div>
  866. <div class="chart-row">
  867. <div class="chart-column">
  868. <canvas id="customerSegmentChart1"></canvas>
  869. </div>
  870. <div class="chart-column">
  871. <canvas id="customerSegmentChart2"></canvas>
  872. </div>
  873. </div>
  874. </div>
  875. <script>
  876. // 客户数量和收入分布
  877. var segmentCtx1 = document.getElementById('customerSegmentChart1').getContext('2d');
  878. new Chart(segmentCtx1, {
  879. type: 'bar',
  880. data: {
  881. labels: <?php echo json_encode($segments); ?>,
  882. datasets: [
  883. {
  884. label: '客户数量',
  885. data: <?php echo json_encode($customer_counts); ?>,
  886. backgroundColor: 'rgba(54, 162, 235, 0.5)',
  887. borderColor: 'rgb(54, 162, 235)',
  888. borderWidth: 1,
  889. yAxisID: 'y-customers'
  890. },
  891. {
  892. label: '销售收入',
  893. data: <?php echo json_encode($revenues); ?>,
  894. backgroundColor: 'rgba(255, 99, 132, 0.5)',
  895. borderColor: 'rgb(255, 99, 132)',
  896. borderWidth: 1,
  897. yAxisID: 'y-revenue'
  898. }
  899. ]
  900. },
  901. options: {
  902. responsive: true,
  903. scales: {
  904. 'y-customers': {
  905. type: 'linear',
  906. position: 'left',
  907. title: {
  908. display: true,
  909. text: '客户数量'
  910. }
  911. },
  912. 'y-revenue': {
  913. type: 'linear',
  914. position: 'right',
  915. title: {
  916. display: true,
  917. text: '销售收入 (元)'
  918. },
  919. grid: {
  920. drawOnChartArea: false
  921. }
  922. }
  923. },
  924. plugins: {
  925. title: {
  926. display: true,
  927. text: '客户细分分布'
  928. }
  929. }
  930. }
  931. });
  932. // 平均单价分布
  933. var segmentCtx2 = document.getElementById('customerSegmentChart2').getContext('2d');
  934. new Chart(segmentCtx2, {
  935. type: 'radar',
  936. data: {
  937. labels: <?php echo json_encode($segments); ?>,
  938. datasets: [{
  939. label: '平均单价',
  940. data: <?php echo json_encode($avg_prices); ?>,
  941. backgroundColor: 'rgba(75, 192, 192, 0.2)',
  942. borderColor: 'rgb(75, 192, 192)',
  943. pointBackgroundColor: 'rgb(75, 192, 192)',
  944. pointBorderColor: '#fff',
  945. pointHoverBackgroundColor: '#fff',
  946. pointHoverBorderColor: 'rgb(75, 192, 192)'
  947. }]
  948. },
  949. options: {
  950. responsive: true,
  951. plugins: {
  952. title: {
  953. display: true,
  954. text: '客户细分平均单价分布'
  955. }
  956. }
  957. }
  958. });
  959. </script>
  960. <?php
  961. }
  962. /**
  963. * 获取产品增长率分析
  964. *
  965. * @param mysqli $conn 数据库连接
  966. * @param string $start_date 开始日期
  967. * @param string $end_date 结束日期
  968. * @param string $period 时间粒度
  969. * @param mixed $employee_filter 业务员过滤条件
  970. * @return array 产品增长率分析数据
  971. */
  972. function getProductGrowthAnalysis($conn, $start_date, $end_date, $period = 'month', $employee_filter = null) {
  973. $groupFormat = getPeriodFormat($period);
  974. // 获取当前期间的数据
  975. $sql = "SELECT
  976. p.ProductName,
  977. SUM(oi.total_price) as current_revenue,
  978. SUM(oi.quantity) as current_quantity,
  979. COUNT(DISTINCT o.id) as current_orders
  980. FROM order_items oi
  981. JOIN products p ON oi.product_id = p.id
  982. JOIN orders o ON oi.order_id = o.id";
  983. if ($employee_filter !== null) {
  984. $sql .= " JOIN customer c ON o.customer_id = c.id";
  985. }
  986. $sql .= " WHERE o.is_deleted = 0 AND oi.is_deleted = 0 AND o.order_date BETWEEN '$start_date' AND '$end_date'";
  987. // 添加业务员过滤
  988. if ($employee_filter !== null) {
  989. if (is_array($employee_filter)) {
  990. if (count($employee_filter) > 0) {
  991. $employee_ids = implode(',', $employee_filter);
  992. $sql .= " AND c.cs_belong IN ($employee_ids)";
  993. }
  994. } else {
  995. $sql .= " AND c.cs_belong = $employee_filter";
  996. }
  997. }
  998. $sql .= " GROUP BY oi.product_id
  999. HAVING current_revenue > 0
  1000. ORDER BY current_revenue DESC
  1001. LIMIT 10";
  1002. $current_data = $conn->query($sql);
  1003. // 计算上一个时间段
  1004. $date1 = new DateTime($start_date);
  1005. $date2 = new DateTime($end_date);
  1006. $interval = $date1->diff($date2);
  1007. $days_diff = $interval->days;
  1008. $prev_end = $date1->format('Y-m-d');
  1009. $prev_start = $date1->modify("-{$days_diff} days")->format('Y-m-d');
  1010. // 获取上一期间的数据
  1011. $sql = "SELECT
  1012. p.ProductName,
  1013. SUM(oi.total_price) as prev_revenue,
  1014. SUM(oi.quantity) as prev_quantity,
  1015. COUNT(DISTINCT o.id) as prev_orders
  1016. FROM order_items oi
  1017. JOIN products p ON oi.product_id = p.id
  1018. JOIN orders o ON oi.order_id = o.id
  1019. WHERE o.is_deleted = 0 AND oi.is_deleted = 0 AND o.order_date BETWEEN '$prev_start' AND '$prev_end'
  1020. GROUP BY oi.product_id";
  1021. $prev_result = $conn->query($sql);
  1022. $prev_data = [];
  1023. while ($row = $prev_result->fetch_assoc()) {
  1024. $prev_data[$row['ProductName']] = $row;
  1025. }
  1026. $growth_data = [];
  1027. while ($current = $current_data->fetch_assoc()) {
  1028. $product_name = $current['ProductName'];
  1029. $prev = isset($prev_data[$product_name]) ? $prev_data[$product_name] : [
  1030. 'prev_revenue' => 0,
  1031. 'prev_quantity' => 0,
  1032. 'prev_orders' => 0
  1033. ];
  1034. $growth_data[] = [
  1035. 'product_name' => $product_name,
  1036. 'current_revenue' => $current['current_revenue'],
  1037. 'current_quantity' => $current['current_quantity'],
  1038. 'current_orders' => $current['current_orders'],
  1039. 'prev_revenue' => $prev['prev_revenue'],
  1040. 'prev_quantity' => $prev['prev_quantity'],
  1041. 'prev_orders' => $prev['prev_orders'],
  1042. 'revenue_growth' => calculateGrowthRate($current['current_revenue'], $prev['prev_revenue']),
  1043. 'quantity_growth' => calculateGrowthRate($current['current_quantity'], $prev['prev_quantity']),
  1044. 'orders_growth' => calculateGrowthRate($current['current_orders'], $prev['prev_orders'])
  1045. ];
  1046. }
  1047. return $growth_data;
  1048. }
  1049. /**
  1050. * 计算增长率
  1051. */
  1052. function calculateGrowthRate($current, $previous) {
  1053. if ($previous == 0) {
  1054. return $current > 0 ? 100 : 0;
  1055. }
  1056. return round((($current - $previous) / $previous) * 100, 2);
  1057. }
  1058. /**
  1059. * 渲染产品增长率分析
  1060. */
  1061. function renderProductGrowthAnalysis($growth_data) {
  1062. ?>
  1063. <div class="chart-container">
  1064. <div class="chart-header">
  1065. <h2 class="chart-title">产品增长率分析</h2>
  1066. <div class="chart-subtitle">与上一时期相比</div>
  1067. </div>
  1068. <table class="data-table">
  1069. <thead>
  1070. <tr>
  1071. <th>产品名称</th>
  1072. <th>当期收入</th>
  1073. <th>收入增长率</th>
  1074. <th>当期销量</th>
  1075. <th>销量增长率</th>
  1076. <th>当期订单数</th>
  1077. <th>订单增长率</th>
  1078. </tr>
  1079. </thead>
  1080. <tbody>
  1081. <?php foreach ($growth_data as $row): ?>
  1082. <tr>
  1083. <td><?php echo htmlspecialchars($row['product_name']); ?></td>
  1084. <td>¥<?php echo number_format($row['current_revenue'], 2); ?></td>
  1085. <td class="<?php echo $row['revenue_growth'] >= 0 ? 'positive' : 'negative'; ?>">
  1086. <?php echo ($row['revenue_growth'] >= 0 ? '+' : '') . $row['revenue_growth']; ?>%
  1087. </td>
  1088. <td><?php echo number_format($row['current_quantity']); ?></td>
  1089. <td class="<?php echo $row['quantity_growth'] >= 0 ? 'positive' : 'negative'; ?>">
  1090. <?php echo ($row['quantity_growth'] >= 0 ? '+' : '') . $row['quantity_growth']; ?>%
  1091. </td>
  1092. <td><?php echo number_format($row['current_orders']); ?></td>
  1093. <td class="<?php echo $row['orders_growth'] >= 0 ? 'positive' : 'negative'; ?>">
  1094. <?php echo ($row['orders_growth'] >= 0 ? '+' : '') . $row['orders_growth']; ?>%
  1095. </td>
  1096. </tr>
  1097. <?php endforeach; ?>
  1098. </tbody>
  1099. </table>
  1100. </div>
  1101. <style>
  1102. .positive {
  1103. color: #4CAF50;
  1104. font-weight: bold;
  1105. }
  1106. .negative {
  1107. color: #f44336;
  1108. font-weight: bold;
  1109. }
  1110. .chart-subtitle {
  1111. font-size: 14px;
  1112. color: #666;
  1113. margin-top: 5px;
  1114. }
  1115. </style>
  1116. <?php
  1117. }
  1118. /**
  1119. * 获取产品购买频率分析
  1120. *
  1121. * @param mysqli $conn 数据库连接
  1122. * @param string $start_date 开始日期
  1123. * @param string $end_date 结束日期
  1124. * @param mixed $employee_filter 业务员过滤条件
  1125. * @return mysqli_result 产品购买频率分析数据
  1126. */
  1127. function getProductPurchaseFrequency($conn, $start_date, $end_date, $employee_filter = null) {
  1128. $sql = "SELECT
  1129. p.ProductName,
  1130. COUNT(DISTINCT o.id) as order_count,
  1131. COUNT(DISTINCT o.customer_id) as customer_count,
  1132. COUNT(DISTINCT o.id) / COUNT(DISTINCT o.customer_id) as purchase_frequency,
  1133. AVG(
  1134. CASE
  1135. WHEN next_order.next_date IS NOT NULL
  1136. THEN DATEDIFF(next_order.next_date, o.order_date)
  1137. ELSE NULL
  1138. END
  1139. ) as avg_days_between_orders
  1140. FROM order_items oi
  1141. JOIN products p ON oi.product_id = p.id
  1142. JOIN orders o ON oi.order_id = o.id";
  1143. if ($employee_filter !== null) {
  1144. $sql .= " JOIN customer c ON o.customer_id = c.id";
  1145. }
  1146. $sql .= " LEFT JOIN (
  1147. SELECT
  1148. o1.customer_id,
  1149. o1.order_date,
  1150. MIN(o2.order_date) as next_date
  1151. FROM orders o1
  1152. LEFT JOIN orders o2 ON o1.customer_id = o2.customer_id
  1153. AND o2.order_date > o1.order_date
  1154. AND o2.is_deleted = 0
  1155. WHERE o1.is_deleted = 0 AND o1.order_date BETWEEN '$start_date' AND '$end_date'
  1156. GROUP BY o1.customer_id, o1.order_date
  1157. ) next_order ON o.customer_id = next_order.customer_id
  1158. AND o.order_date = next_order.order_date
  1159. WHERE o.is_deleted = 0 AND oi.is_deleted = 0 AND o.order_date BETWEEN '$start_date' AND '$end_date'";
  1160. // 添加业务员过滤
  1161. if ($employee_filter !== null) {
  1162. if (is_array($employee_filter)) {
  1163. if (count($employee_filter) > 0) {
  1164. $employee_ids = implode(',', $employee_filter);
  1165. $sql .= " AND c.cs_belong IN ($employee_ids)";
  1166. }
  1167. } else {
  1168. $sql .= " AND c.cs_belong = $employee_filter";
  1169. }
  1170. }
  1171. $sql .= " GROUP BY p.id
  1172. HAVING order_count > 1
  1173. ORDER BY purchase_frequency DESC
  1174. LIMIT 10";
  1175. $result = $conn->query($sql);
  1176. return $result;
  1177. }
  1178. /**
  1179. * 渲染产品购买频率分析
  1180. */
  1181. function renderProductPurchaseFrequency($frequency_data) {
  1182. ?>
  1183. <div class="chart-container">
  1184. <div class="chart-header">
  1185. <h2 class="chart-title">产品购买频率分析</h2>
  1186. </div>
  1187. <table class="data-table">
  1188. <thead>
  1189. <tr>
  1190. <th>产品名称</th>
  1191. <th>订单总数</th>
  1192. <th>购买客户数</th>
  1193. <th>平均购买频率</th>
  1194. <th>平均购买间隔(天)</th>
  1195. </tr>
  1196. </thead>
  1197. <tbody>
  1198. <?php while ($row = $frequency_data->fetch_assoc()): ?>
  1199. <tr>
  1200. <td><?php echo htmlspecialchars($row['ProductName']); ?></td>
  1201. <td><?php echo number_format($row['order_count']); ?></td>
  1202. <td><?php echo number_format($row['customer_count']); ?></td>
  1203. <td><?php echo number_format($row['purchase_frequency'], 2); ?>次/客户</td>
  1204. <td><?php echo $row['avg_days_between_orders'] ? number_format($row['avg_days_between_orders'], 1) : '-'; ?></td>
  1205. </tr>
  1206. <?php endwhile; ?>
  1207. </tbody>
  1208. </table>
  1209. </div>
  1210. <?php
  1211. }
  1212. /**
  1213. * 获取新客户购买产品明细
  1214. *
  1215. * @param mysqli $conn 数据库连接
  1216. * @param string $start_date 开始日期
  1217. * @param string $end_date 结束日期
  1218. * @param int $category_filter 分类过滤
  1219. * @param mixed $employee_filter 业务员过滤条件
  1220. * @return array 新客户购买产品明细数据
  1221. */
  1222. function getNewCustomerProductPurchases($conn, $start_date, $end_date, $category_filter = 0, $employee_filter = null) {
  1223. // 获取新客户ID列表 - 使用cs_dealdate作为判断标准
  1224. $new_customer_sql = "SELECT id
  1225. FROM customer
  1226. WHERE cs_dealdate BETWEEN '$start_date' AND '$end_date'";
  1227. // 添加业务员过滤
  1228. if ($employee_filter !== null) {
  1229. if (is_array($employee_filter)) {
  1230. if (count($employee_filter) > 0) {
  1231. $employee_ids = implode(',', $employee_filter);
  1232. $new_customer_sql .= " AND cs_belong IN ($employee_ids)";
  1233. }
  1234. } else {
  1235. $new_customer_sql .= " AND cs_belong = $employee_filter";
  1236. }
  1237. }
  1238. // 获取符合条件的新客户产品购买数据
  1239. $sql = "SELECT
  1240. p.ProductName,
  1241. p.id as product_id,
  1242. pc.name as category_name,
  1243. COUNT(DISTINCT o.customer_id) as customer_count,
  1244. COUNT(DISTINCT o.id) as order_count,
  1245. SUM(oi.quantity) as total_quantity,
  1246. SUM(oi.total_price) as total_revenue,
  1247. AVG(oi.unit_price) as avg_unit_price
  1248. FROM orders o
  1249. JOIN order_items oi ON o.id = oi.order_id
  1250. JOIN products p ON oi.product_id = p.id
  1251. JOIN product_categories pc ON p.category_id = pc.id
  1252. JOIN customer c ON o.customer_id = c.id
  1253. WHERE o.is_deleted = 0 AND oi.is_deleted = 0 AND o.order_date BETWEEN '$start_date' AND '$end_date'
  1254. AND o.customer_id IN ($new_customer_sql)";
  1255. if ($category_filter > 0) {
  1256. $sql .= " AND p.category_id = $category_filter";
  1257. }
  1258. // 添加业务员过滤
  1259. if ($employee_filter !== null) {
  1260. if (is_array($employee_filter)) {
  1261. if (count($employee_filter) > 0) {
  1262. $employee_ids = implode(',', $employee_filter);
  1263. $sql .= " AND c.cs_belong IN ($employee_ids)";
  1264. }
  1265. } else {
  1266. $sql .= " AND c.cs_belong = $employee_filter";
  1267. }
  1268. }
  1269. $sql .= " GROUP BY p.id
  1270. ORDER BY customer_count DESC, total_revenue DESC
  1271. LIMIT 10";
  1272. $result = $conn->query($sql);
  1273. // 查询新客户总数
  1274. $sql_count = "SELECT
  1275. COUNT(*) as total_new_customers
  1276. FROM ($new_customer_sql) as new_customers";
  1277. $result_count = $conn->query($sql_count);
  1278. $count_row = $result_count->fetch_assoc();
  1279. $new_customer_count = $count_row ? $count_row['total_new_customers'] : 0;
  1280. // 格式化返回数据
  1281. $products = [];
  1282. if ($result) {
  1283. while ($row = $result->fetch_assoc()) {
  1284. $products[] = [
  1285. 'product_name' => $row['ProductName'],
  1286. 'product_id' => $row['product_id'],
  1287. 'category_name' => $row['category_name'],
  1288. 'customer_count' => $row['customer_count'],
  1289. 'order_count' => $row['order_count'],
  1290. 'total_quantity' => $row['total_quantity'],
  1291. 'total_revenue' => $row['total_revenue'],
  1292. 'avg_price' => $row['avg_unit_price']
  1293. ];
  1294. }
  1295. }
  1296. return [
  1297. 'products' => $products,
  1298. 'new_customer_count' => $new_customer_count
  1299. ];
  1300. }