add_action('wp_ajax_moncrm_get_dashboard_data', 'moncrm_get_dashboard_data'); function moncrm_get_dashboard_data() { global $wpdb; $period = intval($_POST['period'] ?? 7); $start = date('Y-m-d 00:00:00', strtotime("-{$period} days")); $end = date('Y-m-d 23:59:59'); $orders = wc_get_orders([ 'limit' => -1, 'status' => ['completed', 'processing'], 'date_created' => $start . '...' . $end, ]); $total = 0; $commandes = 0; $statuts = []; $line_data = []; $line_labels = []; $bar_labels = []; $bar_data = []; $produits = []; for ($i = $period - 1; $i >= 0; $i--) { $date = date('Y-m-d', strtotime("-$i days")); $line_labels[] = $date; $line_data[$date] = 0; } foreach ($orders as $order) { $commandes++; $date = $order->get_date_created()->format('Y-m-d'); $total += $order->get_total(); // Statut $s = wc_get_order_status_name($order->get_status()); $statuts[$s] = ($statuts[$s] ?? 0) + 1; // Line chart if (isset($line_data[$date])) { $line_data[$date] += $order->get_total(); } // Produits foreach ($order->get_items() as $item) { $name = $item->get_name(); $produits[$name] = ($produits[$name] ?? 0) + $item->get_quantity(); } } arsort($produits); $top5 = array_slice($produits, 0, 5, true); foreach ($top5 as $name => $qty) { $bar_labels[] = $name; $bar_data[] = $qty; } $kpis = [ ['label' => 'Commandes', 'value' => $commandes], ['label' => 'Moyenne Panier', 'value' => wc_price($commandes ? $total / $commandes : 0)], // ⛔ Non affiché mais renvoyé ['label' => 'Total Encaissé', 'value' => wc_price($total), 'hidden' => true], ]; $donut_labels = array_keys($statuts); $donut_data = array_values($statuts); $donut_colors = array_map(function () { return '#' . substr(md5(uniqid()), 0, 6); }, $donut_labels); wp_send_json([ 'kpis' => $kpis, 'charts' => [ 'donut' => ['labels' => $donut_labels, 'data' => $donut_data, 'colors' => $donut_colors], 'line' => ['labels' => $line_labels, 'data' => array_values($line_data)], 'bar' => ['labels' => $bar_labels, 'data' => $bar_data], ] ]); }