Custom reports for a Craft Commerce store
On this page
In 2022 I built a Craft Commerce store (on the Craft and Commerce releases current at the time) for a client whose customers do not pay with a card. Community organizations are assigned vouchers, each voucher belongs to a funding source, and a funding source decides which product categories you can order from and whether you are spending dollars or credits. Picking a funding source empties your cart. It is a store, but the thing the client runs it for is accountability: which program paid for which items, going to whom.
Commerce's built-in order export gives you one row per order with the order's own columns. It does not know what a funding source is, it cannot link a row to the voucher that paid for it, and it cannot put line items across columns. Every report I have written for this site since has been some version of adding those three things.
Version one: a Twig template
The first report, three weeks into the build, was a Twig template under templates/reports/ that looped over orders and printed a table. It worked for the client review and I would not do it again. The template ran the full query on every page load, there was no way to download it, and the only permission model was "can you reach this URL".
Version two: a config-driven CSV plugin
In May 2023, a few months after launch, I installed the agency's Reporter plugin. It is a small Craft plugin where config/reporter.php returns an array of reports, each one an element type, criteria, and a transformer closure. Running a report pushes a queue job that batches the element query, writes rows with fputcsv to a temp file, and saves the result as an asset in a volume. Managers get a CP page with a button and a list of past exports. I gave the client's manager group permission to that page the next day, which was the first time a report had a permission model at all.
The itemsOrdered report is one row per line item, with the order's customer, status, funding source and voucher link repeated on each row. Fetching the voucher means reading the order's first adjustment and looking up the code it snapshotted:
'transformer' => function (Order $order) {
$codeUrl = 'No Voucher';
if (isset($order->getAdjustments()[0]->sourceSnapshot['codeKey'])) {
$codeKey = $order->getAdjustments()[0]->sourceSnapshot['codeKey'];
$codeUrl = Code::findOne(['codeKey' => $codeKey])?->getCpEditUrl();
}
return collect($order->lineItems)->map(fn ($item) => [
'Item Name' => $item->description,
'Item Qty' => $item->qty,
'Order Number' => $order->getShortNumber(),
'Order Funding Source' => $order->selectFundingSources->one()?->title,
'Order Funding Link' => $codeUrl,
// ...
])->toArray();
},
The allOrders report wanted the opposite shape, one row per order with the line items spread across columns: #1 Item Name, #1 Item Qty, #2 Item Name, and so on. The plugin derives CSV headers from the first row it transforms, and the first order is almost never the widest one. So I forked the plugin to accept a headers closure and wrote one that finds the order with the most line items and builds the column list from that. It loads every completed order to do it. For this store that is a few hundred rows and it has not mattered. I know it is the wrong shape and I would write a MAX(COUNT(*)) query the day it does.
Version three: a module with a date range
Queued exports are all or nothing. By 2024 the managers' real question was "show me last quarter", and the answer should not be "export everything and filter it in Excel". So in May 2024 I wrote a statistics module: a CP section with its own nav item, a date range, a sort order, pagination, and an "Export All (CSV)" button that hands the same filters to a controller action. The service runs the Commerce element query with dateCreated(['and', ">= $dateFrom", "< $dateTo"]), the Twig template renders the page, and the controller streams the CSV:
public function actionGetOrders($page, $sortOrder, $dateFrom, $dateTo, $perPage)
{
$items = Statistics::$instance->customerData
->getOrders($page, $sortOrder, $dateFrom, $dateTo, $perPage);
return $this->_asCSV($items['items'], 'orders'.date('Y-m-d').'.csv');
}
A voucher report sits next to it: every code, its original and remaining balance, and the organization it was assigned to. In February this year the client asked for inventory, so a productInventory report over Variant elements with status(null) went into the Reporter config, because managers wanted disabled variants on it too.
The query count
Last week the items-ordered CSV started failing on wide date ranges. The symptom was a Cloudflare error, because the origin took longer than Cloudflare's 100 second limit to answer. The cause was the transformer: each row touched the customer, both addresses, the line items, the adjustments and the funding source relation, and every one of those was a query inside the loop. Adding eager loading to the two order queries fixed it:
$orders = Order::find()
->isCompleted(true)
->dateCreated(['and', ">= $dateFrom", "< $dateTo"])
->with(['customer', 'shippingAddress', 'billingAddress', 'lineItems', 'adjustments', 'selectFundingSources'])
->all();
On a local copy with 129 orders and 366 line items that went from 1,510 queries in 0.743 seconds to 780 queries in 0.415 seconds, with identical output. It should have been there from the first version.
What I would tell myself in 2022
Start with the CSV plugin, not a template. A report that cannot be downloaded is a demo.
Decide the row early. One row per order and one row per line item are different reports, and the client will want both.
Put the custom relations in the transformer and eager load them in the query. The transformer is where the client's vocabulary lives; the with() is what keeps it from timing out.
Give the client a date range before they ask. They will ask.