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: }
config/routes.php
PHP · Click a line number to comment · Tap a line to comment@@ -1,9 +1,12 @@
<?php
use App\Controller\Admin\OrderController;
Added: use App\Controller\Admin\OrderExportController;
use App\Middleware\RequireAdmin;
$router->group('/admin', function ($router) {
$router->get('/orders', [OrderController::class, 'index']);
$router->get('/orders/{id}', [OrderController::class, 'show']);
}, middleware: [RequireAdmin::class]);
Added:
Added: $router->get('/admin/orders/export', [OrderExportController::class, 'export']);
tests/OrderExportTest.php
PHP · Click a line number to comment · Tap a line to comment@@ -0,0 +1,14 @@
Added: <?php
Added:
Added: namespace Tests;
Added:
Added: class OrderExportTest extends TestCase
Added: {
Added: public function testExportStartsWithAHeaderRow(): void
Added: {
Added: $response = $this->get('/admin/orders/export');
Added:
Added: $this->assertSame(200, $response->status());
Added: $this->assertStringStartsWith("id,customer,email,total,created", $response->body());
Added: }
Added: }