Which rows are real business? Cleaning test orders, bots, refunds and late data with written rules
TL;DR
Difficulty: Intermediate
A shop's order table holds carts, test orders, cancellations and orders that change weeks later. None of that is dirty data, and none of it is revenue as you mean it.
- Write every business rule down first, with an owner, a reason and a version, then code it once.
- Classify rows, never delete them: test, staff, cancelled, sale.
- Report refunds by order month for performance and by refund month for cash, and say which.
- Store times in UTC and convert to Europe/Dublin only when a person needs a date.
- Late refunds can lawfully arrive 34 days after an order, and goodwill refunds later still, so keep months provisional and close them on day 60.
Every shop database has a column called total, and adding it up gives a number that looks like revenue. It is not revenue until someone decides which rows count, which day they belong to and what happened to them afterwards. This chapter turns those decisions into ten written rules, a dbt model and tests, and walks one invented Limerick shop's October from €167,536 of raw totals to €123,675 of net revenue.
Revenue is a definition, not a column
Every shop database has a column called total. Add it up for a month and you get a number. It looks like revenue. It is not revenue yet, because nobody has decided which rows count.
The question this chapter answers is the one every owner eventually asks: which rows in my data are real business, and which only look like it? A test order placed by your developer looks exactly like a customer order. A cart abandoned by a bot sits in the same table as a paid order. A refund issued six weeks later changes a month that everyone thought was finished. None of these rows is broken. The values are clean, the dates parse, the amounts add up. They are simply not what the report means by "sales".
That is what makes this kind of cleaning different from the chapters before it. Standardising values makes the same thing look the same. Outlier detection asks whether one value is plausible. Business rule cleaning asks a question the data cannot answer on its own: does this row belong in the number a report is about to show someone? Only the business can define that. The data engineer's job is to get the definition written down, agreed, coded once, tested and applied the same way everywhere.
A few terms first. A business rule is a written decision about what a row means, for example "an order placed with a staff email address is not a customer order". Gross sales here means the value of orders customers placed and did not cancel, including VAT and delivery. Net revenue means gross sales minus refunds, minus anything that is not a sale of goods (such as gift cards sold), minus VAT. A reporting period is the month or week a number belongs to. Each gets its own section below, each with a worked example.
Example: three October revenue figures at Shannonside Home
Shannonside Home is the invented online homeware shop in Limerick that runs through this whole series, at shannonsidehome.example. Niamh owns it. Callum is her developer and data engineer. The shop runs on Ruby on Rails and Solidus with PostgreSQL. All numbers in this chapter are invented for the example.
At the start of November, Niamh asks a simple question: "What did we sell in October?" She gets three answers.
| Source | What was summed | October figure |
|---|---|---|
| A quick SQL query by Callum | sum(total) over spree_orders with completed_at in October | €167,536 |
| GA4 (Google Analytics 4) | purchase revenue in the standard reports | about 15% fewer purchases than the shop, so a lower figure |
| The number this chapter builds | real customer orders, by Irish date, after cancellations, refunds, gift cards and VAT | €123,675 |
The gap between the first and the last line is €43,861. Not one row in the database is wrong. Every euro of the difference comes from a rule: which rows count, which day they belong to, and what happened to them afterwards. The GA4 gap has its own causes (consent, blockers, attribution), which when analytics, ads and orders disagree takes apart one by one. This chapter is about the shop's own data, the source of truth, and how to turn its rows into a number Niamh can put in front of her accountant and her bank.
By the end, Callum will have ten written rules, a dbt model that applies them, tests that prove them and a waterfall chart that shows exactly where the €43,861 went.
Write each rule down before you code it
A business rule that lives only in a SQL query is a guess that happens to run. Someone copies the query, changes one line, and two dashboards now disagree by €1,722 with nobody able to say why.
So every rule starts as a written entry in the rule register, the list of cleaning rules introduced in when to clean data and when to leave it alone. For business rules the register needs a few fields more than for technical ones, because the definition is a business decision and somebody outside engineering has to own it:
| Field | What it holds |
|---|---|
| Rule id | A short stable name, for example R2_test_orders |
| Definition | One or two plain sentences a shop owner can read and agree to |
| Owner | The person who decides the rule (for revenue rules, usually the owner or the finance lead, not the engineer) |
| Reason | Why the rule exists, in business words |
| Applies to | Which reports and models use it |
| Action | Exclude, flag, move to another period, or adjust |
| Version and date | When the rule last changed, so old reports can be explained |
| Test | The test that proves the code does what the definition says |
The most important column is "Action". Business rules almost never delete anything. They classify. A test order is kept in the warehouse with a label that says "test", and every report that wants customer orders filters on that label. If the rule ever changes, you change the label logic and rerun, and nothing is lost. A later chapter in this series covers the layered pipeline that makes this safe: raw data that is never overwritten, and clean layers built on top.
Example: rule R2 written out
Here is the entry Callum writes for test orders, agreed with Niamh in ten minutes:
| Field | Entry |
|---|---|
| Rule id | R2_test_orders |
| Definition | An order is a test order if it was flagged as a test in the shop admin, or its email is on the internal accounts list with the reason "test", or it was paid with the internal test payment method. Test orders are never customer revenue. |
| Owner | Niamh |
| Reason | Callum and Niamh place real orders on the live shop to check new features and payment changes. About 40 a year. |
| Applies to | Every revenue, order count, conversion and customer report; every conversion sent to ad platforms |
| Action | Classify as test; exclude from all customer and revenue figures |
| Version and date | v2, 3 November 2026 (v1 matched only the email list) |
| Test | test_order_classification in the dbt project |
The register for this chapter ends up with ten rules:
| Rule | Short definition | Action |
|---|---|---|
| R1 | Only rows with a completion time are orders | exclude carts |
| R2 | Test orders are not customer orders | classify test, exclude |
| R3 | Staff purchases are real revenue but not customer behaviour | flag, keep in revenue, exclude from customer metrics |
| R4 | Card testing and other bot activity is not demand | exclude from carts, sessions and payment metrics |
| R5 | Cancelled orders are not sales | classify cancelled, exclude from gross sales |
| R6 | Refunds reduce net revenue, dated by order for performance and by refund for cash | subtract |
| R7 | Gift cards sold are not product revenue until they are redeemed | subtract at sale |
| R8 | A day is an Irish day (Europe/Dublin) | convert before grouping |
| R9 | A month stays provisional until day 60, then it is closed | label, snapshot, adjust |
| R10 | Every amount keeps its currency; reports convert at the order date's rate | convert, never mix |
The rest of this chapter takes them in turn.
The orders table is not a list of orders
The first rule surprises almost everyone who opens a Solidus database for the first time. The table spree_orders holds every order the shop has ever started, and in Solidus an order starts the moment a visitor puts something in the basket. A cart is an order in state cart. It moves through address, delivery, payment and confirm, and only when checkout succeeds does it reach complete, at which point completed_at is set1.
After completion the order can still move: to canceled, to awaiting_return, to returned, and in rare cases back from cancelled to resumed1. Alongside the main state, Solidus keeps a payment_state (balance_due, paid, credit_owed, failed or void) and a shipment_state2.
So rule R1 is simple and catches the biggest error of all: an order is a row with a completion time. Everything else is a cart, abandoned or still open.
Example: 14,620 rows, 2,004 orders
Callum counts the rows in spree_orders created in October. This query is PostgreSQL, run against a read replica of the shop database:
-- PostgreSQL: what is actually in spree_orders for October?
select
state,
count(*) as order_rows,
count(*) filter (where completed_at is not null) as with_completion_time
from spree_orders
where created_at >= '2026-10-01' and created_at < '2026-11-01'
group by state
order by order_rows desc;
| state | order_rows | with_completion_time |
|---|---|---|
| cart | 9,870 | 0 |
| address | 1,402 | 0 |
| payment | 1,214 | 0 |
| delivery | 128 | 0 |
| complete | 1,824 | 1,824 |
| returned | 108 | 108 |
| awaiting_return | 51 | 51 |
canceled | 21 | 21 |
| confirm | 2 | 0 |
| total | 14,620 | 2,004 |
(This query groups by creation date, which is close enough for a first look. The real model groups by completion date, as the rules below explain.)
A report that counts rows says Shannonside took 14,620 orders in October. The shop took 2,004, and even that number still contains test orders and cancellations. Notice also the 1,214 rows stuck in payment. That number is far too high for a shop of this size, and it is the first clue for rule R4.
Test orders and staff orders are not the same thing
Every shop that is looked after properly has test orders on the live system. The developer checks that a new payment method works end to end, the owner checks that the confirmation email looks right. Staging environments catch most problems, but some things (the real payment provider, the real email delivery, the real courier label) can only be proven on production. Shannonside places about 40 such orders a year.
Staff purchases are a different thing. When Callum buys a lamp for his flat at the staff discount, that is a real sale: real money, real goods, real VAT. It belongs in revenue. It does not belong in conversion rate, customer counts, average order value for customers or the conversions sent to Google Ads and Meta, because it tells you nothing about how customers behave. So R2 excludes and R3 flags, and the difference matters.
How do you recognise them? No single signal is enough. Callum combines four:
| Signal | Catches | Misses |
|---|---|---|
| A flag set in the shop admin at the time | anything the person remembers to flag | anything they forget |
| Email on an internal accounts list | orders placed while logged in or with a known address | a test with a new throwaway address |
| Internal test payment method | test orders by design | staff purchases paid by card |
| Shipping address is the office | most staff purchases | tests that never ship |
The strongest fix is at the source. Since Solidus 4.5 (released 19 February 2025), orders, payments, refunds and several other tables carry two JSON columns, customer_metadata and admin_metadata3. That gives Callum a place to record "internal: test" or "internal: staff" on the order itself, at the moment it completes, instead of guessing months later.
He adds a subscriber to the shop. Solidus publishes an order_finalized event when an order completes, and its own mailers listen to it through Omnes::Subscriber4. Callum's subscriber follows the same pattern.
# app/subscribers/internal_order_subscriber.rb
class InternalOrderSubscriber
include Omnes::Subscriber
handle :order_finalized,
with: :flag_internal_order,
id: :shannonside_flag_internal_order
def flag_internal_order(event)
order = event[:order]
reason = InternalOrderRule.new(order).reason
return if reason.nil?
order.update_column(
:admin_metadata,
(order.admin_metadata || {}).merge("internal" => reason)
)
end
end
# app/models/internal_order_rule.rb
class InternalOrderRule
STAFF_DOMAIN = "@shannonsidehome.example"
TEST_PAYMENT_METHOD = "Internal test"
def initialize(order)
@order = order
end
# Returns "test", "staff" or nil
def reason
return "test" if @order.payments.any? { |p| p.payment_method&.name == TEST_PAYMENT_METHOD }
email = @order.email.to_s.strip.downcase
return "staff" if email.end_with?(STAFF_DOMAIN)
nil
end
end
# config/initializers/internal_order_subscriber.rb
Rails.application.config.to_prepare do
InternalOrderSubscriber.new.subscribe_to(Spree::Bus)
end
Written test first, as everything in the shop is: a spec that completes an order paid with the test method and expects admin_metadata["internal"] to be "test", and one with a staff email that expects "staff". If you have not worked this way before, test driven development explained shows the rhythm.
The same flag then does a second job. The server side purchase event that Shannonside sends to GA4 and the ad platforms checks it, so a test order never reaches Google Ads as a conversion. A test order that is counted as a conversion teaches the bidding algorithm that the office in Limerick is a great audience, which is the wrong lesson.
The source fix only works from the day it goes live. Five years of history still need the warehouse rule, so the warehouse model uses all four signals, and the metadata flag simply becomes the most reliable one.
Example: five October orders that were not customers
Callum keeps a small seed file in the dbt project, seeds/internal_accounts.csv, owned by Niamh:
email,reason,valid_from,note
callum@shannonsidehome.example,staff,2021-03-01,developer
niamh@shannonsidehome.example,staff,2021-03-01,owner
qa+payments@shannonsidehome.example,test,2024-06-10,payment checks
In October the rules find five orders:
| Order | Signal | Total | Rule | Action |
|---|---|---|---|---|
| R318840 | test payment method, flagged test | €24.00 | R2 | excluded |
| R319112 | test payment method | €96.00 | R2 | excluded |
| R320457 | email qa+payments@... | €130.00 | R2 | excluded |
| R319675 | staff email, shipped to Callum's home | €71.40 | R3 | kept in revenue, flagged |
| R321003 | staff email, shipped to the office | €44.80 | R3 | kept in revenue, flagged |
The three test orders total €24.00 + €96.00 + €130.00 = €250.00. They leave revenue entirely. The two staff purchases (€116.20 together) stay in revenue but drop out of the customer conversion rate, the customer count and the customer average order value.
Bots in the shop and bots in analytics
Bots touch shop data in two places, and the rules differ.
In the shop database, the bot that matters most is card testing. Stripe describes it as fraud where someone tries to find out whether stolen card details are valid, usually by attempting many small payments5. A shop's checkout is a convenient test bench. The traces it leaves in Solidus are carts that never complete, a burst of payments in state failed, and orders sitting in payment with payment_state failed. Because these orders never get a completion time, rule R1 already keeps them out of revenue. They still poison three other numbers: the count of carts started (and therefore the cart abandonment rate), the payment failure rate and, through the browser, sessions.
So rule R4 says: activity that matches a card testing pattern is classified as bot and excluded from carts, payment failure rates and checkout funnels. The pattern is defined in business words first: "more than 20 failed payment attempts from carts with no product page view, within one hour". Then it is coded.
In GA4, Google already removes traffic from known bots and spiders, using its own research and the International Spiders and Bots List maintained by the Interactive Advertising Bureau (IAB). You cannot switch this off, and you cannot see how much was removed6. That is fine for most uses, but it means GA4 session counts are already cleaned by a rule you cannot inspect. Write that down in the register as an external rule.
Internal traffic is yours to define. GA4 lets you mark visits from your own IP addresses with a traffic_type parameter and then exclude them with a data filter7. Read Google's warning before you activate one: once an exclude filter is active, the excluded data is never processed and never reaches the BigQuery export either8. That is the opposite of the classify, never delete principle. Callum's choice is to activate the filter for the office IP address, which is unambiguously internal, and to rely on the shop database's staff flag for everything that matters financially, because Niamh also browses the shop from her phone on the train, and no IP filter catches that.
Example: the night of 14 October
On 14 October, between 1am and 4am, Shannonside's checkout received 2,140 payment attempts on 1,186 carts. 2,131 failed. No product page was viewed from any of those sessions, and every cart held the same €4.95 candle wick trimmer.
| Metric for October | Before R4 | After R4 |
|---|---|---|
| Carts started | 14,620 | 13,434 |
| Payment attempts | 4,310 | 2,170 |
| Payment failure rate | 2,268 ÷ 4,310 = 52.6% | 137 ÷ 2,170 = 6.3% |
| Completed orders | 2,004 | 2,004 |
Revenue does not move at all. The payment failure rate falls from a panic level to a normal one. Without R4, Callum would have spent a day investigating the payment provider for a problem that was not there, and Niamh would have read a cart abandonment rate that made the checkout look broken. The fix at the source here is not a data rule at all: rate limits and the payment provider's fraud screening, which Callum switched on the next morning.
Cancelled, refunded, returned: three different things
These three words are used as if they meant the same. In the data they are three different events, recorded in different tables, with different effects on the numbers.
| What happened | In Solidus | Effect on reporting |
|---|---|---|
| Cancelled: the order is called off before it ships | order state becomes canceled, canceled_at is set, payments are voided or refunded1 | not a sale: out of gross sales (R5) |
| Returned: goods come back and money goes back | a return authorisation, a customer return with spree_return_items, a reimbursement in spree_reimbursements, and refunds in spree_refunds linked to it | the sale happened, the refund reduces net revenue (R6) |
| Refunded without a return: money goes back, goods do not | a row in spree_refunds with no reimbursement_id, typically with a refund reason such as "damaged in transit" | the sale happened, the refund reduces net revenue (R6) |
| Partly refunded | a refund smaller than the payment, or a return of some items only | only the refunded amount is subtracted |
| Short shipped: one item cannot be sent | a unit cancel adjustment on a completed order | the order total itself goes down (see the section on orders that change) |
The refund tables in Solidus link to payments, not directly to orders: spree_refunds.payment_id points to spree_payments, which carries order_id. A refund that came from a return also carries a reimbursement_id9. A query that joins refunds straight to orders by some other path will miss goodwill refunds or count return refunds twice.
The second half of R6 is the one that causes the most arguments: which date does a refund belong to? There are two honest answers, and you need both.
- By order date (the cohort view): the refund belongs to the month the order was placed. This answers "how good was October's business?" and is the right basis for return rates, marketing performance and product decisions.
- By refund date (the cash view): the refund belongs to the month the money went out. This matches the payment provider's settlement files and is usually what the accounts use.
Neither is wrong. Mixing them in one report is wrong. The rule register says which one each report uses, and the report says it in its subtitle. Returns in eCommerce goes deep on return rates and their cost; here the point is the data rule.
Put together, net revenue for a period is:
where is net revenue excluding VAT, is the total of all completed orders in the period (including VAT and delivery), is the total of cancelled and test orders in that set, is refunds linked to those orders, is the value of gift cards sold in those orders, and is the VAT rate as a decimal (0.23 in Ireland for standard rated goods). Dividing by removes VAT from an amount that includes it, which Foundations: percentages explains step by step. The formula assumes every item is standard rated. A shop that also sells zero rated goods takes VAT off line by line instead, using the tax columns Solidus stores on each order.
Example: four orders, four outcomes
Four Shannonside orders from 9 October, each €84.00 including VAT:
| Order | What happened | Gross sales | Refund | Contribution to net revenue |
|---|---|---|---|---|
| A | kept | €84.00 | €0.00 | €84.00 ÷ 1.23 = €68.29 |
| B | cancelled on 9 October before dispatch | €0.00 | n/a | €0.00 |
| C | one of two cushions returned, refund 2 November | €84.00 | €42.00 | €42.00 ÷ 1.23 = €34.15 |
| D | arrived chipped, €16.80 refunded as goodwill, no return | €84.00 | €16.80 | €67.20 ÷ 1.23 = €54.63 |
Gross sales are €252.00 (B never counted). Refunds are €58.80. Net revenue is €252.00 minus €58.80, which is €193.20, divided by 1.23: €157.07, which matches €68.29 + €0.00 + €34.15 + €54.63.
In the cohort view, all €58.80 of refunds belong to October. In the cash view, order C's €42.00 belongs to November, because that is when the money left. Here is the query for the cohort view, in PostgreSQL:
-- PostgreSQL: refunds per order, whatever their origin
select
p.order_id,
sum(r.amount) as refunded_total,
sum(r.amount) filter (where r.reimbursement_id is not null) as refunded_for_returns,
sum(r.amount) filter (where r.reimbursement_id is null) as refunded_goodwill,
max(r.created_at) as last_refund_at_utc
from spree_refunds r
join spree_payments p on p.id = r.payment_id
group by p.order_id;
Gift cards, vouchers and discount codes
Three things that look alike at the checkout behave very differently in the numbers.
A discount code lowers the price. The order total is already lower, Solidus records the promotion as an adjustment (in promo_total), and there is nothing more to clean. The only rule is to report revenue after discounts, never the list price.
A gift card sold is not a sale of goods. The customer has handed over money for the right to buy something later. Product revenue happens when the card is redeemed, when the recipient buys a lamp with it. If you count the gift card when it is sold and again when it is spent, the same €50 appears twice.
Solidus has store credit built in, with its own payment method and the spree_store_credits table. Sellable gift cards usually come from an extension or a custom product. Either way, rule R7 in the warehouse is: a line item that is a gift card is excluded from product revenue at sale, and the order that redeems it counts in full, because its total is a real sale of goods.
How gift cards are treated in the accounts, and for VAT, is your accountant's decision, not the data engineer's. The VAT side has its own vocabulary. Irish VAT law, following the EU rules on vouchers, separates single purpose vouchers (SPVs) from multi purpose vouchers (MPVs), and Revenue explains that the type decides when VAT is due and how it can be deducted10. A Shannonside gift card that can be spent on anything in the shop, at different VAT rates, is most likely a multi purpose voucher, but that is exactly the kind of judgement to confirm with the accountant and then write into the rule register. The data rule follows the accounting rule, never the other way round. This is general information, not tax or legal advice.
Example: a €50 gift card from sale to redemption
On 20 October, a customer buys a €50 gift card together with a €34 vase. Order total: €84.00. On 6 November, the recipient spends the card on a €60 throw and pays the other €10 by card.
| Date | Order | Order total | Gift card rule | Product revenue incl. VAT |
|---|---|---|---|---|
| 20 October | vase plus gift card | €84.00 | €50.00 excluded at sale | €34.00 |
| 6 November | throw, paid €50 by gift card and €10 by card | €60.00 | redemption counts in full | €60.00 |
Without R7, October shows €84.00 and November €60.00, so €144.00 of revenue for €94.00 of goods. With R7, October shows €34.00 and November €60.00, which is €94.00, the real value of the goods sold. In October as a whole, Shannonside sold 40 gift cards worth €1,800, which R7 takes out of product revenue.
Where a day ends: time zones and the day boundary
A sale happens at a moment. A report puts it on a day. The rule that connects the two, R8, decides which day, and therefore which month, a sale belongs to.
Rails stores times in the database as UTC (Coordinated Universal Time) by default11, and on PostgreSQL a Rails datetime column is by default a timestamp without time zone12. So spree_orders.completed_at holds a UTC time with no label saying so. If you group by completed_at::date, you group by UTC days.
For a shop in Limerick, a UTC day is wrong for half the year. In summer, Irish clocks run one hour ahead of UTC. Winter time, when Ireland is back on Greenwich Mean Time, starts on the last Sunday in October13, which in 2026 was 25 October. An order placed at 12.30am on 1 October in Limerick is stored as 11.30pm on 30 September. In a UTC report it lands in September.
The fix in PostgreSQL is two conversions in a row, and the order matters14.
-- PostgreSQL: completed_at is a UTC time without a zone label
select
number,
completed_at as completed_at_utc,
(completed_at at time zone 'UTC') at time zone 'Europe/Dublin' as completed_at_ie,
((completed_at at time zone 'UTC') at time zone 'Europe/Dublin')::date as order_date_ie
from spree_orders
where completed_at is not null;
The first at time zone 'UTC' tells PostgreSQL "this naked timestamp is UTC" and turns it into a timestamp with time zone. The second converts that moment into the wall clock time in Ireland. Use the zone name Europe/Dublin, never a fixed offset like +01, so summer time is handled for every date in five years of history.
Every other source has its own clock, and the rule has to cover each of them:
| Source | How it stores time | What R8 does |
|---|---|---|
Solidus (completed_at, created_at) | UTC, no zone label | convert as above |
| GA4 BigQuery export | event_timestamp in microseconds UTC; event_date already in the property's time zone15 | use event_date only if the property is set to Dublin; otherwise convert event_timestamp |
| 3PL warehouse CSV | local time in Limerick, no zone | attach Europe/Dublin first, then convert to UTC for storage |
| Stripe and PayPal settlement files | each provider documents its own; check per file | convert to UTC at load |
| dbt microbatch models | dbt assumes event_time and batch boundaries are UTC16 | store UTC, convert to Irish dates only in the reporting layer |
In BigQuery, the same conversion is DATE(TIMESTAMP_MICROS(event_timestamp), 'Europe/Dublin'), because DATE accepts a time zone as its second argument and otherwise uses UTC17.
The principle behind the table: store moments in UTC, always with the knowledge that they are UTC, and convert to a local calendar only at the last step, when a person needs a date.
Example: the nine orders that moved to September
Callum compares the two ways of counting October:
| Way of counting | Window in Irish time | Orders |
|---|---|---|
| UTC month | 1am on 1 October to the end of 31 October | 1,995 |
| Irish month (R8) | midnight on 1 October to the end of 31 October | 2,004 |
Nine orders, placed between midnight and 1am on 1 October in Ireland, are in September in the UTC report. At €84 each that is €756 of October's sales booked in the wrong month. At the other end of the month nothing moves, because the clocks went back on 25 October and from then on Irish time and UTC are the same. The same check in March would show the shift the other way round.
Example: Black Friday at 11.30pm
Black Friday 2026 is 27 November. A customer in Limerick orders at 11.30pm Irish time. In Berlin, where Central European Time is one hour ahead of Ireland in November, it is already 12.30am on Saturday.
If Shannonside's figures are ever combined with a partner's in Germany, or if an agency in Berlin builds the dashboard and leaves the reporting time zone at its own default, this order moves from Friday to Saturday, and Black Friday looks weaker than it was. The rule is to agree one reporting time zone per business and write it into the register: Shannonside reports in Europe/Dublin, and a group that combines several countries reports each shop in its own zone and says so.
Late data: returns arrive days later, refunds weeks later
Some facts about October only exist in November. A return can only happen after delivery. A refund can only happen after the return. The data about the return may arrive later still.
Stream processing research has a precise vocabulary for this. Event time is when something happened in the world. Processing time is when your system learns about it. The gap between them is never zero and often large, and a pipeline that pretends otherwise gives wrong answers18. A later chapter in this series covers streaming and watermarks in depth. For a monthly report the consequence is simpler: October's net revenue keeps changing for weeks after October ends.
How long? Irish consumer law gives the answer for the main case. For goods bought online, the cancellation period runs until 14 days after the goods come into the customer's possession19. After telling the shop, the customer has 14 days to send the goods back20. The shop must refund within 14 days of being told about the cancellation, but for goods it may hold the refund back until it has the goods again or the customer shows proof of sending them, whichever comes first21. So the longest ordinary delay between an order on the last day of the month and its refund is:
where is the number of days from order to refund, is the delivery time, is the 14 day cancellation period, is the 14 days the shop has to refund after being told, is the 14 days the customer has to send the goods back and is the return delivery time. The takes whichever is later: the refund deadline, or the day the goods are back when the customer gives no proof of posting. It is a sum of durations with one comparison; Foundations: ratios and rates covers working with rates and periods if you want the groundwork.
With Shannonside's three day delivery each way, by An Post:
where is the number of days, and .
So an order placed on 31 October can lawfully be refunded as late as 4 December. Faulty goods, goodwill gestures and payment disputes can come later still, which is why the closing rule in the next section waits much longer than 34 days.
Shannonside's 3PL adds a data delay on top. Its daily CSV of shipments and returns lists returns up to five days after the warehouse received them. In the database, a return that physically arrived on 4 December may appear on 9 December.
The engineering answer to late data is to reprocess a window, not only the newest rows. In dbt Core 1.9 and later, the microbatch incremental strategy does this directly: you name the column that holds event time, the batch size, and a lookback of how many earlier batches to reprocess on every run to catch late arriving records16. On PostgreSQL it needs a unique_key16:
-- models/intermediate/int_3pl__returns.sql (dbt Core 1.9+, dbt-postgres)
{{ config(
materialized = 'incremental',
incremental_strategy = 'microbatch',
event_time = 'received_at_utc',
batch_size = 'day',
lookback = 6,
begin = '2021-11-01',
unique_key = 'return_line_id'
) }}
select
return_line_id,
order_number,
sku_shop,
quantity,
received_at_utc,
loaded_at
from {{ ref('stg_3pl__returns') }}
Three details make this correct rather than nearly correct. The upstream staging model must also declare event_time = 'received_at_utc', or dbt cannot filter it per batch and scans the whole table every time16. The staging model is where the 3PL's local time without a zone gets Europe/Dublin attached and becomes UTC, because dbt assumes batch boundaries are UTC. And lookback = 6 covers the five day delay with one day to spare.
GA4's own export behaves the same way, on a shorter scale: Google keeps updating each daily events_YYYYMMDD table for late events for a few days after its date22. A pipeline that loads yesterday's table once and never looks back again misses those events.
Example: how October's net revenue settled
Callum runs the October net revenue query every Monday and keeps each answer. This is the cohort view: refunds on October orders, whenever they happen.
| Reported on | Refunds known on October orders | October net revenue excl. VAT |
|---|---|---|
| 2 November | €1,450 | €132,577 |
| 9 November | €4,620 | €130,000 |
| 16 November | €8,050 | €127,211 |
| 23 November | €10,190 | €125,472 |
| 30 November | €11,560 | €124,358 |
| 7 December | €12,180 | €123,854 |
| 14 December | €12,380 | €123,691 |
| 21 December | €12,400 | €123,675 |
Each line is the formula from earlier with the refunds known that day. For 2 November: €166,320 minus €1,450 minus €1,800 leaves €163,070, and €163,070 ÷ 1.23 = €132,577. The refunds column includes both return refunds and goodwill refunds, which together end at €12,400.
A report produced on 2 November overstated October by €8,902 (€132,577 against €123,675). Nobody made a mistake. The data simply was not complete yet.
Closing a month, and reopening it honestly
If October keeps moving until Christmas, when can anyone use it? The answer is a closing rule, R9, agreed with Niamh and her accountant, with three stages:
| Stage | When | What the report says | What may change |
|---|---|---|---|
| Provisional | from day 1 after month end | "Provisional: refunds still arriving" in the title | everything |
| Soft close | day 7 | first official number, shared with the business | late refunds, returns and corrections |
| Hard close | day 60 | final number, used for the year's figures | nothing in place; later changes become adjustments |
Day 60 is not arbitrary. It covers the 34 day legal path from the previous section with plenty to spare for goodwill refunds, the 3PL's five day delay and a week for payment disputes and slow corrections.
After the hard close, a late change is never written silently into October. There are two honest options, and the register says which one applies:
- Adjust in the current period. The €97 refund that arrives in January for an October order appears in January as a line called "adjustments to closed periods". October stays as reported. This is how most accounts work.
- Restate the closed period. October is recalculated, a new version is published, and the change is logged with the reason and the difference. This is right when a rule was wrong, not when life simply went on. A later chapter in this series covers restatements and how to explain them to the people who read your reports.
Either way, you need to know what was reported. So every time a month passes a stage, Callum stores the number as it was published:
-- PostgreSQL: one row per published figure, never updated
create table reported_monthly_revenue (
period_month date not null,
stage text not null check (stage in ('provisional', 'soft_close', 'hard_close', 'restatement')),
version integer not null,
net_revenue numeric(12,2) not null,
refunds_included numeric(12,2) not null,
rule_version text not null,
published_at timestamptz not null default now(),
note text,
primary key (period_month, version)
);
The rule_version column ties each published number to the rules that produced it, so in a year's time someone can explain why the soft close said one thing and the hard close another. A later chapter in this series covers keeping history like this in depth, including snapshots of every changed row.
Example: the late sideboard refund
October closed hard on 30 December at €123,675 net. On 14 January, a customer who bought a €490 sideboard on 28 October finally gets a partial refund of €119 after a long dispute about a scratch, agreed as goodwill.
Under option 1, January's report shows "adjustments to closed periods: minus €96.75" (that is €119 ÷ 1.23, net of VAT), and October stays at €123,675. Under option 2, October would be restated to €123,578, version 4, with the note "goodwill refund agreed 14 January after the hard close". Niamh chooses option 1 for late refunds and keeps option 2 for genuine rule errors. Both choices go into the register, so nobody has to remember them.
Orders that change after they are complete
A completed order is not frozen. In Solidus, an admin can short ship an item that turns out to be out of stock, or cancel a single unit. The class that does this describes itself as "all of the actions one can take to modify an Order after it is complete"23. The order total changes, an adjustment appears, and updated_at moves. Addresses get corrected, a payment is captured later, a shipment is split.
Two rules follow.
First, load changes, not only new rows. An incremental load that picks up orders by completed_at sees each order once and never notices that its total fell from €112 to €84 a week later. It must pick up rows by updated_at (with a lookback, as above), or better, capture every change from the database log. A later chapter in this series covers incremental loading and change data capture.
Second, decide which version each report wants. For revenue, the current state of the order is right: the customer paid €84, not €112. For checking what was sent to the ad platforms on the day, the state at completion is right. The Kimball accumulating snapshot is the classic model for this: one row per order (or order line), with a date column for each milestone, completed, shipped, returned, refunded, updated as the order moves along its life24. Callum's fct_orders follows that shape.
Example: the short shipped vase
Order R320118, completed on 17 October at €112.00: a €28 vase and an €84 lamp. On 19 October the warehouse finds the last vase broken. Callum short ships it and Solidus refunds €28.
| Load method | What October shows for R320118 |
|---|---|
Load by completed_at, once | €112.00 (wrong, forever) |
Load by updated_at with lookback | €84.00 |
| Accumulating snapshot | €84.00 now, with completed_total €112.00 and short_shipped_at 19 October kept for analysis |
The first method overstates October by €28 for this one order. Across a month with a dozen short shipments, it is hundreds of euro that no refund table will ever explain, because the money went back through the order itself.
The order's currency and the reporting currency
Shannonside sells in euro, but since spring it has also shown sterling prices to customers in Northern Ireland (an invented detail for this example). Solidus stores the order's currency on each order. A sum of total across euro and sterling is meaningless, and the error is silent because both are just numbers.
Rule R10 says: every amount is stored with its currency. The reporting currency is EUR. Each foreign order is converted at a dated reference rate for its order date, stored in a rates table, and the rate used is kept on the row. The settlement file from the payment provider shows the rate the money was actually converted at, which will differ slightly, and that difference belongs in a finance reconciliation, not in the sales report. Standardising values covers rates tables and why you never mix currencies in one sum. The waterfall below already includes Shannonside's sterling orders, converted to euro this way.
Example: one order to Belfast
On 12 October a customer in Belfast pays £72.00. Callum's rates table holds an invented rate of 1.15 euro per pound for that day. The order counts as £72.00 × 1.15 = €82.80 in the EUR report, and the row keeps currency = 'GBP', amount_original = 72.00 and fx_rate = 1.15. Summed naively, it would have added 72.00 as if it were euro, which is €10.80 too little for one order.
October from raw rows to reportable revenue
Now all the rules run together. Callum's intermediate model classifies every order once, and every report reads the classification instead of reinventing it. This is dbt on PostgreSQL:
-- models/intermediate/int_orders__classified.sql
with orders as (
select * from {{ ref('stg_solidus__orders') }}
),
internal_accounts as (
select lower(trim(email)) as email, reason
from {{ ref('internal_accounts') }}
),
orders_local as (
select
o.*,
(o.completed_at_utc at time zone 'UTC') at time zone 'Europe/Dublin' as completed_at_ie
from orders o
)
select
o.order_id,
o.order_number,
o.completed_at_utc,
o.completed_at_ie,
date_trunc('month', o.completed_at_ie)::date as order_month_ie,
o.currency,
o.total,
case
when o.completed_at_utc is null then 'not_an_order' -- R1
when o.internal_flag = 'test'
or ia.reason = 'test'
or o.paid_with_test_method then 'test' -- R2
when o.state = 'canceled' then 'cancelled' -- R5
else 'sale'
end as order_class,
coalesce(o.internal_flag = 'staff' or ia.reason = 'staff', false) as is_staff_purchase, -- R3
'{{ var("revenue_rules_version") }}' as rule_version
from orders_local o
left join internal_accounts ia
on ia.email = lower(trim(o.email))
The staging model stg_solidus__orders has already renamed completed_at to completed_at_utc, extracted admin_metadata ->> 'internal' into internal_flag and worked out paid_with_test_method from the payments. Every rule carries its register id in a comment, and the rules version travels with every row, set once in dbt_project.yml as a variable.
The rules can also be documented where the model is documented, using dbt's meta config, which since dbt 1.10 sits under config25.
# models/intermediate/_int_orders.yml
models:
- name: int_orders__classified
description: "One row per Solidus order, classified by the revenue rules R1 to R5."
config:
meta:
owner: "Niamh"
rule_register: "R1, R2, R3, R5 (v2, 3 November 2026)"
columns:
- name: order_class
description: "not_an_order, test, cancelled or sale"
data_tests:
- accepted_values:
arguments: # dbt 1.10.5 and later
values: ['not_an_order', 'test', 'cancelled', 'sale']
The mart model then subtracts refunds by order (R6), gift card lines (R7) and VAT, all grouped by order_month_ie (R8). Here is October, as it stood at the hard close:
| Step | Rule | Amount | Running total |
|---|---|---|---|
Sum of total, completed in the UTC month | none | €167,536 | €167,536 |
| Orders from the first hour of 1 October Irish time | R8 | plus €756 | €168,292 |
| Test orders | R2 | minus €250 | €168,042 |
| Cancelled orders | R5 | minus €1,722 | €166,320 |
| Gross sales, 1,980 orders | €166,320 | ||
| Refunds on October orders (returns) | R6 | minus €12,040 | €154,280 |
| Goodwill refunds without a return | R6 | minus €360 | €153,920 |
| Gift cards sold | R7 | minus €1,800 | €152,120 |
| VAT (€152,120 × 23 ÷ 123) | minus €28,445 | €123,675 | |
| Net revenue excl. VAT | €123,675 |
The VAT line uses the formula from earlier: with , the VAT inside an amount that includes it is the amount times , so €152,120 × 23 ÷ 123 = €28,445.20.
The two staff purchases stay inside the €166,320, flagged. Gross sales of €166,320 over 1,980 orders is exactly the €84 average order value Shannonside is known for, and that agreement is itself a useful check.
The biggest single step is VAT, which is not cleaning at all, just a definition. The biggest cleaning step is refunds, which is also the one that arrives late. The small steps, the test orders and the time zone shift, are small in money but large in trust: they are the ones that make two reports disagree for no reason anyone can explain.
Testing the rules so they stay true
A rule that is not tested drifts. Somebody adds a new payment method called "Internal test (new)", the exact string match fails, and test orders quietly flow back into revenue.
dbt Core 1.8 and later supports unit tests: you give a model fixed input rows and state the exact output you expect, without touching real data26. One test per rule, built from the edge cases you already know about:
# models/intermediate/_int_orders.yml (continued)
unit_tests:
- name: test_order_classification
description: "R1, R2, R3 and R5 classify orders as the rule register says."
model: int_orders__classified
given:
- input: ref('stg_solidus__orders')
format: dict
rows:
- {order_id: 1, order_number: R1, completed_at_utc: null, state: cart, email: a@shop.example, internal_flag: null, paid_with_test_method: false, currency: EUR, total: 40}
- {order_id: 2, order_number: R2, completed_at_utc: '2026-10-05 10:00:00', state: complete, email: b@shop.example, internal_flag: test, paid_with_test_method: false, currency: EUR, total: 24}
- {order_id: 3, order_number: R3, completed_at_utc: '2026-10-05 11:00:00', state: complete, email: ' QA+payments@shannonsidehome.example', internal_flag: null, paid_with_test_method: false, currency: EUR, total: 95}
- {order_id: 4, order_number: R4, completed_at_utc: '2026-10-06 09:00:00', state: complete, email: callum@shannonsidehome.example, internal_flag: null, paid_with_test_method: false, currency: EUR, total: 61.2}
- {order_id: 5, order_number: R5, completed_at_utc: '2026-10-07 14:00:00', state: canceled, email: c@shop.example, internal_flag: null, paid_with_test_method: false, currency: EUR, total: 70}
- {order_id: 6, order_number: R6, completed_at_utc: '2026-09-30 23:30:00', state: complete, email: d@shop.example, internal_flag: null, paid_with_test_method: false, currency: EUR, total: 72}
- input: ref('internal_accounts')
format: dict
rows:
- {email: callum@shannonsidehome.example, reason: staff}
- {email: qa+payments@shannonsidehome.example, reason: test}
expect:
format: dict
rows:
- {order_id: 1, order_class: not_an_order, is_staff_purchase: false}
- {order_id: 2, order_class: test, is_staff_purchase: false}
- {order_id: 3, order_class: test, is_staff_purchase: false}
- {order_id: 4, order_class: sale, is_staff_purchase: true}
- {order_id: 5, order_class: cancelled, is_staff_purchase: false}
- {order_id: 6, order_class: sale, is_staff_purchase: false}
Row 3 tests that the email match survives capital letters and a leading space, which duplicates and entity resolution shows is how real emails arrive. Row 6 is the 11.30pm UTC order on 30 September. A second unit test on the same model expects its order_month_ie to be 1 October 2026, which pins rule R8. A later chapter in this series covers testing pipelines in full, from unit tests to data contracts.
Alongside the unit tests, two data tests run against real data every night: the share of orders classified test per month must stay below 1%, and gross sales from the warehouse must match the sum of Stripe and PayPal settlements for the same orders within a small agreed tolerance. The first catches a broken rule. The second catches a rule that nobody thought of.
Conclusion
Business rule cleaning is where data engineering meets the business. The values in the rows are fine. What needs deciding is what the rows mean: an order is a row with a completion time, a test order is not a customer, a staff purchase is revenue but not behaviour, a cancellation is not a sale, a refund belongs to the order's month for performance and to its own month for cash, a gift card is revenue only when it is spent, a day is an Irish day, and a month is not final until day 60.
None of those rules can be found in the data. Each one is written into the register with an owner and a reason, coded once in a model every report reads, flagged at the source where the shop can do it, tested with the edge cases you already know, and versioned so that last quarter's number can still be explained next year. Do that, and the €43,861 between a quick sum and the real October stops being a mystery. It becomes a waterfall that anyone can read.
