PR Review Lab · Export Orders to CSV From the Admin Panel

25:00left of 25:00

Export Orders to CSV From the Admin Panel

Finance exports orders every month by asking an engineer to run a query. This adds an export endpoint the admin panel links to, with an optional from date. Each row has the order, the customer, the total, and the number of items. There's a test that checks the header row.

Asrc/Controller/Admin/OrderExportController.php1 of 3

Files Changed

src/Controller/Admin/

config/

tests/

src/Controller/Admin/OrderExportController.php

PHP · Click a line number to comment · Tap a line to comment
@@ -0,0 +1,31 @@
Added: <?php
Added:
Added: namespace App\Controller\Admin;
Added:
Added: use App\Db;
Added:
Added: class OrderExportController
Added: {
Added: public function __construct(private Db $db)
Added: {
Added: }
Added:
Added: public function export(): void
Added: {
Added: $from = $_GET['from'] ?? '1970-01-01';
Added: $orders = $this->db->query(
Added: "SELECT id, customer_name, email, total_cents, created_at FROM orders WHERE created_at >= '$from' ORDER BY id"
Added: )->fetchAll();
Added:
Added: header('Content-Type: text/csv');
Added: header('Content-Disposition: attachment; filename="orders.csv"');
Added:
Added: $out = fopen('php://output', 'w');
Added: fputcsv($out, ['id', 'customer', 'email', 'total', 'created']);
Added: foreach ($orders as $order) {
Added: $items = $this->db->query("SELECT COUNT(*) FROM order_items WHERE order_id = {$order['id']}")->fetchColumn();
Added: fputcsv($out, [$order['id'], $order['customer_name'], $order['email'], $order['total_cents'] / 100, $order['created_at'], $items]);
Added: }
Added: fclose($out);
Added: }
Added: }