statistics_products.php 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  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.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.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.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.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.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.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.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.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">
  369. <div class="chart-header">
  370. <h2 class="chart-title">热门产品</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.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.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. WHERE o1.order_date BETWEEN '$start_date' AND '$end_date'
  1155. GROUP BY o1.customer_id, o1.order_date
  1156. ) next_order ON o.customer_id = next_order.customer_id
  1157. AND o.order_date = next_order.order_date
  1158. WHERE o.order_date BETWEEN '$start_date' AND '$end_date'";
  1159. // 添加业务员过滤
  1160. if ($employee_filter !== null) {
  1161. if (is_array($employee_filter)) {
  1162. if (count($employee_filter) > 0) {
  1163. $employee_ids = implode(',', $employee_filter);
  1164. $sql .= " AND c.cs_belong IN ($employee_ids)";
  1165. }
  1166. } else {
  1167. $sql .= " AND c.cs_belong = $employee_filter";
  1168. }
  1169. }
  1170. $sql .= " GROUP BY p.id
  1171. HAVING order_count > 1
  1172. ORDER BY purchase_frequency DESC
  1173. LIMIT 10";
  1174. $result = $conn->query($sql);
  1175. return $result;
  1176. }
  1177. /**
  1178. * 渲染产品购买频率分析
  1179. */
  1180. function renderProductPurchaseFrequency($frequency_data) {
  1181. ?>
  1182. <div class="chart-container">
  1183. <div class="chart-header">
  1184. <h2 class="chart-title">产品购买频率分析</h2>
  1185. </div>
  1186. <table class="data-table">
  1187. <thead>
  1188. <tr>
  1189. <th>产品名称</th>
  1190. <th>订单总数</th>
  1191. <th>购买客户数</th>
  1192. <th>平均购买频率</th>
  1193. <th>平均购买间隔(天)</th>
  1194. </tr>
  1195. </thead>
  1196. <tbody>
  1197. <?php while ($row = $frequency_data->fetch_assoc()): ?>
  1198. <tr>
  1199. <td><?php echo htmlspecialchars($row['ProductName']); ?></td>
  1200. <td><?php echo number_format($row['order_count']); ?></td>
  1201. <td><?php echo number_format($row['customer_count']); ?></td>
  1202. <td><?php echo number_format($row['purchase_frequency'], 2); ?>次/客户</td>
  1203. <td><?php echo $row['avg_days_between_orders'] ? number_format($row['avg_days_between_orders'], 1) : '-'; ?></td>
  1204. </tr>
  1205. <?php endwhile; ?>
  1206. </tbody>
  1207. </table>
  1208. </div>
  1209. <?php
  1210. }
  1211. /**
  1212. * 获取新客户购买产品明细
  1213. *
  1214. * @param mysqli $conn 数据库连接
  1215. * @param string $start_date 开始日期
  1216. * @param string $end_date 结束日期
  1217. * @param int $category_filter 分类过滤
  1218. * @param mixed $employee_filter 业务员过滤条件
  1219. * @return array 新客户购买产品明细数据
  1220. */
  1221. function getNewCustomerProductPurchases($conn, $start_date, $end_date, $category_filter = 0, $employee_filter = null) {
  1222. // 获取符合条件的新客户订单
  1223. $sql = "SELECT
  1224. p.ProductName,
  1225. p.id as product_id,
  1226. pc.name as category_name,
  1227. COUNT(DISTINCT o.customer_id) as customer_count,
  1228. COUNT(DISTINCT o.id) as order_count,
  1229. SUM(oi.quantity) as total_quantity,
  1230. SUM(oi.total_price) as total_revenue,
  1231. AVG(oi.unit_price) as avg_unit_price
  1232. FROM orders o
  1233. JOIN order_items oi ON o.id = oi.order_id
  1234. JOIN products p ON oi.product_id = p.id
  1235. JOIN product_categories pc ON p.category_id = pc.id
  1236. JOIN customer c ON o.customer_id = c.id
  1237. WHERE o.order_date BETWEEN '$start_date' AND '$end_date'
  1238. AND o.id IN (
  1239. SELECT MIN(id)
  1240. FROM orders
  1241. WHERE order_date BETWEEN '$start_date' AND '$end_date'";
  1242. if ($employee_filter !== null) {
  1243. $sql .= " AND customer_id IN (
  1244. SELECT id FROM customer WHERE ";
  1245. if (is_array($employee_filter)) {
  1246. if (count($employee_filter) > 0) {
  1247. $employee_ids = implode(',', $employee_filter);
  1248. $sql .= "cs_belong IN ($employee_ids))";
  1249. } else {
  1250. $sql .= "1=1)";
  1251. }
  1252. } else {
  1253. $sql .= "cs_belong = $employee_filter)";
  1254. }
  1255. }
  1256. $sql .= " GROUP BY customer_id
  1257. )";
  1258. if ($category_filter > 0) {
  1259. $sql .= " AND p.category_id = $category_filter";
  1260. }
  1261. // 添加业务员过滤
  1262. if ($employee_filter !== null) {
  1263. if (is_array($employee_filter)) {
  1264. if (count($employee_filter) > 0) {
  1265. $employee_ids = implode(',', $employee_filter);
  1266. $sql .= " AND c.cs_belong IN ($employee_ids)";
  1267. }
  1268. } else {
  1269. $sql .= " AND c.cs_belong = $employee_filter";
  1270. }
  1271. }
  1272. $sql .= " GROUP BY p.id
  1273. ORDER BY customer_count DESC, total_revenue DESC";
  1274. $result = $conn->query($sql);
  1275. // 查询新客户总数
  1276. $sql_count = "SELECT
  1277. COUNT(DISTINCT o.customer_id) as total_new_customers
  1278. FROM orders o
  1279. JOIN customer c ON o.customer_id = c.id
  1280. WHERE o.order_date BETWEEN '$start_date' AND '$end_date'
  1281. AND o.id IN (
  1282. SELECT MIN(id)
  1283. FROM orders
  1284. WHERE order_date BETWEEN '$start_date' AND '$end_date'";
  1285. if ($employee_filter !== null) {
  1286. $sql_count .= " AND customer_id IN (
  1287. SELECT id FROM customer WHERE ";
  1288. if (is_array($employee_filter)) {
  1289. if (count($employee_filter) > 0) {
  1290. $employee_ids = implode(',', $employee_filter);
  1291. $sql_count .= "cs_belong IN ($employee_ids))";
  1292. } else {
  1293. $sql_count .= "1=1)";
  1294. }
  1295. } else {
  1296. $sql_count .= "cs_belong = $employee_filter)";
  1297. }
  1298. }
  1299. $sql_count .= " GROUP BY customer_id
  1300. )";
  1301. if ($employee_filter !== null) {
  1302. if (is_array($employee_filter)) {
  1303. if (count($employee_filter) > 0) {
  1304. $employee_ids = implode(',', $employee_filter);
  1305. $sql_count .= " AND c.cs_belong IN ($employee_ids)";
  1306. }
  1307. } else {
  1308. $sql_count .= " AND c.cs_belong = $employee_filter";
  1309. }
  1310. }
  1311. $result_count = $conn->query($sql_count);
  1312. $count_row = $result_count->fetch_assoc();
  1313. $new_customer_count = $count_row ? $count_row['total_new_customers'] : 0;
  1314. // 格式化返回数据
  1315. $products = [];
  1316. if ($result) {
  1317. while ($row = $result->fetch_assoc()) {
  1318. $products[] = [
  1319. 'product_name' => $row['ProductName'],
  1320. 'product_id' => $row['product_id'],
  1321. 'category_name' => $row['category_name'],
  1322. 'customer_count' => $row['customer_count'],
  1323. 'order_count' => $row['order_count'],
  1324. 'total_quantity' => $row['total_quantity'],
  1325. 'total_revenue' => $row['total_revenue'],
  1326. 'avg_price' => $row['avg_unit_price']
  1327. ];
  1328. }
  1329. }
  1330. return [
  1331. 'products' => $products,
  1332. 'new_customer_count' => $new_customer_count
  1333. ];
  1334. }