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/London only when a person needs a date.
  • Late refunds can lawfully arrive 48 days after an order, 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 shop's October from £143,597 of raw totals to £108,608 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 Wrenfield Home

Wrenfield Home is the invented online homeware shop in Leeds that runs through this whole series, at wrenfieldhome.example. Priya 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, Priya asks a simple question: "What did we sell in October?" She gets three answers.

SourceWhat was summedOctober figure
A quick SQL query by Callumsum(total) over spree_orders with completed_at in October£143,597
GA4 (Google Analytics 4)purchase revenue in the standard reportsabout 15% fewer purchases than the shop, so a lower figure
The number this chapter buildsreal customer orders, by UK date, after cancellations, refunds, gift cards and VAT£108,608

The gap between the first and the last line is £34,989. Not one row in the database is wrong. Every pound 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 Priya 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 £34,989 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,470 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:

FieldWhat it holds
Rule idA short stable name, for example R2_test_orders
DefinitionOne or two plain sentences a shop owner can read and agree to
OwnerThe person who decides the rule (for revenue rules, usually the owner or the finance lead, not the engineer)
ReasonWhy the rule exists, in business words
Applies toWhich reports and models use it
ActionExclude, flag, move to another period, or adjust
Version and dateWhen the rule last changed, so old reports can be explained
TestThe 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 Priya in ten minutes:

FieldEntry
Rule idR2_test_orders
DefinitionAn 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.
OwnerPriya
ReasonCallum and Priya place real orders on the live shop to check new features and payment changes. About 40 a year.
Applies toEvery revenue, order count, conversion and customer report; every conversion sent to ad platforms
ActionClassify as test; exclude from all customer and revenue figures
Version and datev2, 3 November 2026 (v1 matched only the email list)
Testtest_order_classification in the dbt project

The register for this chapter ends up with ten rules:

RuleShort definitionAction
R1Only rows with a completion time are ordersexclude carts
R2Test orders are not customer ordersclassify test, exclude
R3Staff purchases are real revenue but not customer behaviourflag, keep in revenue, exclude from customer metrics
R4Card testing and other bot activity is not demandexclude from carts, sessions and payment metrics
R5Cancelled orders are not salesclassify cancelled, exclude from gross sales
R6Refunds reduce net revenue, dated by order for performance and by refund for cashsubtract
R7Gift cards sold are not product revenue until they are redeemedsubtract at sale
R8A day is a UK day (Europe/London)convert before grouping
R9A month stays provisional until day 60, then it is closedlabel, snapshot, adjust
R10Every amount keeps its currency; reports convert at the order date's rateconvert, 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.

Tap or click to open full screen and move around

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;
stateorder_rowswith_completion_time
cart9,8700
address1,4020
payment1,2140
delivery1280
complete1,8241,824
returned108108
awaiting_return5151
canceled2121
confirm20
total14,6202,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 Wrenfield 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. Wrenfield 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:

SignalCatchesMisses
A flag set in the shop admin at the timeanything the person remembers to flaganything they forget
Email on an internal accounts listorders placed while logged in or with a known addressa test with a new throwaway address
Internal test payment methodtest orders by designstaff purchases paid by card
Shipping address is the officemost staff purchasestests 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: :wrenfield_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 = "@wrenfieldhome.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 Wrenfield 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 Leeds 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 Priya:

email,reason,valid_from,note
callum@wrenfieldhome.example,staff,2021-03-01,developer
priya@wrenfieldhome.example,staff,2021-03-01,owner
qa+payments@wrenfieldhome.example,test,2024-06-10,payment checks

In October the rules find five orders:

OrderSignalTotalRuleAction
R318840test payment method, flagged test£24.00R2excluded
R319112test payment method£96.00R2excluded
R320457email qa+payments@...£95.00R2excluded
R319675staff email, shipped to Callum's home£61.20R3kept in revenue, flagged
R321003staff email, shipped to the office£38.40R3kept in revenue, flagged

The three test orders total £24.00 + £96.00 + £95.00 = £215.00. They leave revenue entirely. The two staff purchases (£99.60 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 Priya 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, Wrenfield'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.50 candle wick trimmer.

Metric for OctoberBefore R4After R4
Carts started14,62013,434
Payment attempts4,3102,170
Payment failure rate2,268 ÷ 4,310 = 52.6%137 ÷ 2,170 = 6.3%
Completed orders2,0042,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 Priya 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 happenedIn SolidusEffect on reporting
Cancelled: the order is called off before it shipsorder state becomes canceled, canceled_at is set, payments are voided or refunded1not a sale: out of gross sales (R5)
Returned: goods come back and money goes backa return authorisation, a customer return with spree_return_items, a reimbursement in spree_reimbursements, and refunds in spree_refunds linked to itthe sale happened, the refund reduces net revenue (R6)
Refunded without a return: money goes back, goods do nota 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 refundeda refund smaller than the payment, or a return of some items onlyonly the refunded amount is subtracted
Short shipped: one item cannot be senta unit cancel adjustment on a completed orderthe 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:

Rnet=G−C−F−Vgift1+vR_{\text{net}} = \frac{G - C - F - V_{\text{gift}}}{1 + v}

where RnetR_{\text{net}} is net revenue excluding VAT, GG is the total of all completed orders in the period (including VAT and delivery), CC is the total of cancelled and test orders in that set, FF is refunds linked to those orders, VgiftV_{\text{gift}} is the value of gift cards sold in those orders, and vv is the VAT rate as a decimal (0.20 in the UK for standard rated goods). Dividing by 1+v1 + v 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 Wrenfield orders from 9 October, each £72.00 including VAT:

OrderWhat happenedGross salesRefundContribution to net revenue
Akept£72.00£0.00£72.00 ÷ 1.2 = £60.00
Bcancelled on 9 October before dispatch£0.00n/a£0.00
Cone of two cushions returned, refund 2 November£72.00£36.00£36.00 ÷ 1.2 = £30.00
Darrived chipped, £14.40 refunded as goodwill, no return£72.00£14.40£57.60 ÷ 1.2 = £48.00

Gross sales are £216.00 (B never counted). Refunds are £50.40. Net revenue is £216.00 minus £50.40, which is £165.60, divided by 1.2: £138.00, which matches £60.00 + £0.00 + £30.00 + £48.00.

In the cohort view, all £50.40 of refunds belong to October. In the cash view, order C's £36.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 £40 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. Since 1 January 2019, UK law separates single purpose vouchers, where VAT is due when the voucher is sold, from multi purpose vouchers, where VAT is due when the voucher is redeemed. HMRC's information sheet sets out the rules, and the legislation is Schedule 10B of the VAT Act 199410. A Wrenfield gift card that can be spent on anything in the shop, at different VAT rates, is most likely multi purpose, 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 £40 gift card from sale to redemption

On 20 October, a customer buys a £40 gift card together with a £32 vase. Order total: £72.00. On 6 November, the recipient spends the card on a £52 throw and pays the other £12 by card.

DateOrderOrder totalGift card ruleProduct revenue incl. VAT
20 Octobervase plus gift card£72.00£40.00 excluded at sale£32.00
6 Novemberthrow, paid £40 by gift card and £12 by card£52.00redemption counts in full£52.00

Without R7, October shows £72.00 and November £52.00, so £124.00 of revenue for £84.00 of goods. With R7, October shows £32.00 and November £52.00, which is £84.00, the real value of the goods sold. In October as a whole, Wrenfield sold 40 gift cards worth £1,600, 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 Leeds, a UTC day is wrong for half the year. From the last Sunday in March to the last Sunday in October the UK is on British Summer Time, one hour ahead of UTC. In 2026 the clocks went forward on 29 March and back on 25 October13. An order placed at 12.30am on 1 October in Leeds 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/London' as completed_at_uk,
    ((completed_at at time zone 'UTC') at time zone 'Europe/London')::date as order_date_uk
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 London. Use the zone name Europe/London, 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:

SourceHow it stores timeWhat R8 does
Solidus (completed_at, created_at)UTC, no zone labelconvert as above
GA4 BigQuery exportevent_timestamp in microseconds UTC; event_date already in the property's time zone15use event_date only if the property is set to London; otherwise convert event_timestamp
3PL warehouse CSVlocal time in Leeds, no zoneattach Europe/London first, then convert to UTC for storage
Stripe and PayPal settlement fileseach provider documents its own; check per fileconvert to UTC at load
dbt microbatch modelsdbt assumes event_time and batch boundaries are UTC16store UTC, convert to UK dates only in the reporting layer

In BigQuery, the same conversion is DATE(TIMESTAMP_MICROS(event_timestamp), 'Europe/London'), 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 countingWindow in UK timeOrders
UTC month1am on 1 October to the end of 31 October1,995
UK month (R8)midnight on 1 October to the end of 31 October2,004

Nine orders, placed between midnight and 1am on 1 October in the UK, are in September in the UTC report. At £72 each that is £648 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 UK 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 Leeds orders at 11.30pm UK time. In Vienna, where Central European Time is one hour ahead of the UK in November, it is already 12.30am on Saturday.

If Wrenfield's figures are ever combined with a partner's in Austria, or if an agency in Vienna 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: Wrenfield reports in Europe/London, 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? UK consumer law gives the answer for the main case. For goods bought online, the customer can cancel within 14 days after the goods arrive19. After telling the shop, they have 14 more days to send the goods back20. The shop must refund within 14 days after it gets the goods back, or after the customer provides evidence of sending them21. Add delivery and the return journey and you get the longest ordinary delay between an order on the last day of the month and its refund:

L=dout+w+s+dback+pL = d_{\text{out}} + w + s + d_{\text{back}} + p

where LL is the number of days from order to refund, doutd_{\text{out}} is the delivery time, ww is the 14 day cancellation period, ss is the 14 days the customer has to send the goods back, dbackd_{\text{back}} is the return delivery time and pp is the 14 days the shop has to refund. It is a plain sum of durations; Foundations: ratios and rates covers working with rates and periods if you want the groundwork.

With Wrenfield's three day delivery each way:

L=3+14+14+3+14=48L = 3 + 14 + 14 + 3 + 14 = 48

where L=48L = 48 is the number of days, dout=dback=3d_{\text{out}} = d_{\text{back}} = 3 and w=s=p=14w = s = p = 14.

So an order placed on 31 October can lawfully be refunded as late as 18 December. Faulty goods and payment disputes can come later still, which is why the closing rule in the next section waits longer than 48 days.

Wrenfield'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/London 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 onRefunds known on October ordersOctober net revenue excl. VAT
2 November£1,240£116,433
9 November£3,950£114,175
16 November£6,880£111,733
23 November£8,710£110,208
30 November£9,620£109,450
7 December£10,050£109,092
14 December£10,410£108,792
21 December£10,630£108,608

Each line is the formula from earlier with the refunds known that day. For 2 November: £142,560 minus £1,240 minus £1,600 leaves £139,720, and £139,720 ÷ 1.2 = £116,433. The refunds column includes both return refunds and goodwill refunds, which together end at £10,630.

A report produced on 2 November overstated October by £7,825 (£116,433 against £108,608). Nobody made a mistake. The data simply was not complete yet.

Line chart for the invented example shop. It shows October's net revenue excluding VAT as reported on each Monday from 2 November to 21 December. It starts at 116,433 pounds on 2 November and falls as refunds for October orders arrive: 114,175 on 9 November, 111,733 on 16 November, 110,208 on 23 November, 109,450 on 30 November, 109,092 on 7 December, 108,792 on 14 December and 108,608 on 21 December. Most of the change happens in the first four weeks. Tap or click to open full screen and move around

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 Priya and her accountant, with three stages:

StageWhenWhat the report saysWhat may change
Provisionalfrom day 1 after month end"Provisional: refunds still arriving" in the titleeverything
Soft closeday 7first official number, shared with the businesslate refunds, returns and corrections
Hard closeday 60final number, used for the year's figuresnothing in place; later changes become adjustments

Day 60 is not arbitrary. It covers the 48 day legal path from the previous section, 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:

  1. Adjust in the current period. The £85 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.
  2. 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 £108,608 net. On 14 January, a customer who bought a £420 sideboard on 28 October finally gets a partial refund of £102 after a long dispute about a scratch, agreed as goodwill.

Under option 1, January's report shows "adjustments to closed periods: minus £85.00" (that is £102 ÷ 1.2, net of VAT), and October stays at £108,608. Under option 2, October would be restated to £108,523, version 4, with the note "goodwill refund agreed 14 January after the hard close". Priya 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 £96 to £72 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 £72, not £96. 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 £96.00: a £24 vase and a £72 lamp. On 19 October the warehouse finds the last vase broken. Callum short ships it and Solidus refunds £24.

Load methodWhat October shows for R320118
Load by completed_at, once£96.00 (wrong, forever)
Load by updated_at with lookback£72.00
Accumulating snapshot£72.00 now, with completed_total £96.00 and short_shipped_at 19 October kept for analysis

The first method overstates October by £24 for this one order. Across a month with a dozen short shipments, it is hundreds of pounds that no refund table will ever explain, because the money went back through the order itself.

The order's currency and the reporting currency

Wrenfield sells in pounds, but since spring it has also shown euro prices to customers in Ireland (an invented detail for this example). Solidus stores the order's currency on each order. A sum of total across pounds and euros 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 GBP. 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 Wrenfield's euro orders, converted to pounds this way.

Example: one order to Galway

On 12 October a customer in Galway pays €96.00. Callum's rates table holds an invented rate of 0.87 pounds per euro for that day. The order counts as €96.00 × 0.87 = £83.52 in the GBP report, and the row keeps currency = 'EUR', amount_original = 96.00 and fx_rate = 0.87. Summed naively, it would have added £96.00, which is £12.48 too much 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/London' as completed_at_uk
    from orders o
)

select
    o.order_id,
    o.order_number,
    o.completed_at_utc,
    o.completed_at_uk,
    date_trunc('month', o.completed_at_uk)::date as order_month_uk,
    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: "Priya"
        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_uk (R8). Here is October, as it stood at the hard close:

StepRuleAmountRunning total
Sum of total, completed in the UTC monthnone£143,597£143,597
Orders from the first hour of 1 October UK timeR8plus £648£144,245
Test ordersR2minus £215£144,030
Cancelled ordersR5minus £1,470£142,560
Gross sales, 1,980 orders£142,560
Refunds on October orders (returns)R6minus £10,320£132,240
Goodwill refunds without a returnR6minus £310£131,930
Gift cards soldR7minus £1,600£130,330
VAT (£130,330 ÷ 6)minus £21,722£108,608
Net revenue excl. VAT£108,608

The VAT line uses the formula from earlier: with v=0.20v = 0.20, the VAT inside an amount that includes it is the amount times v÷(1+v)=0.2÷1.2=1÷6v \div (1 + v) = 0.2 \div 1.2 = 1 \div 6, so £130,330 ÷ 6 = £21,721.67.

The two staff purchases stay inside the £142,560, flagged. Gross sales of £142,560 over 1,980 orders is exactly the £72 average order value Wrenfield is known for, and that agreement is itself a useful check.

Waterfall chart for the invented example shop. The raw sum of order totals for the UTC month is 143,597 pounds. Moving to UK dates adds 648. Test orders remove 215 and cancelled orders 1,470, giving gross sales of 142,560 pounds for 1,980 orders. Refunds for returns remove 10,320, goodwill refunds 310 and gift cards sold 1,600. VAT removes 21,722, leaving net revenue excluding VAT of 108,608 pounds. Tap or click to open full screen and move around

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: GBP, 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: GBP, total: 24}
          - {order_id: 3, order_number: R3, completed_at_utc: '2026-10-05 11:00:00', state: complete, email: ' QA+payments@wrenfieldhome.example', internal_flag: null, paid_with_test_method: false, currency: GBP, total: 95}
          - {order_id: 4, order_number: R4, completed_at_utc: '2026-10-06 09:00:00', state: complete, email: callum@wrenfieldhome.example, internal_flag: null, paid_with_test_method: false, currency: GBP, 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: GBP, 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: GBP, total: 72}
      - input: ref('internal_accounts')
        format: dict
        rows:
          - {email: callum@wrenfieldhome.example, reason: staff}
          - {email: qa+payments@wrenfieldhome.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_uk 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 a UK 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 £34,989 between a quick sum and the real October stops being a mystery. It becomes a waterfall that anyone can read.

If your revenue figures change depending on who ran the query, book the free workshop: we write your shop's revenue rules together and map where each one belongs, and the first two weeks of work are on me.

Sources

  1. 1.

    Solidus, core/lib/spree/core/state_machines/order.rb (the order state machine and its states), GitHub, solidusio/solidus, main branch, accessed 23 November 2026, https://github.com/solidusio/solidus/blob/main/core/lib/spree/core/state_machines/order.rb

  2. 2.

    Solidus, core/app/models/spree/order_updater.rb (payment_state values balance_due, paid, credit_owed, failed, void), GitHub, solidusio/solidus, accessed 23 November 2026, https://github.com/solidusio/solidus/blob/main/core/app/models/spree/order_updater.rb

  3. 3.

    Solidus, AddMetadataToSpreeResources migration (customer_metadata and admin_metadata on orders, payments, refunds and other resources) and CHANGELOG for Solidus v4.5.0, 19 February 2025, GitHub, https://github.com/solidusio/solidus/blob/main/core/db/migrate/20250129061658_add_metadata_to_spree_resources.rb

  4. 4.

    Solidus, core/app/subscribers/spree/order_confirmation_mailer_subscriber.rb (an Omnes subscriber handling order_finalized), GitHub, solidusio/solidus, accessed 23 November 2026, https://github.com/solidusio/solidus/blob/main/core/app/subscribers/spree/order_confirmation_mailer_subscriber.rb

  5. 5.

    Stripe, Protect yourself from card testing, Stripe Docs, accessed 23 November 2026, https://docs.stripe.com/disputes/prevention/card-testing

  6. 6.

    Google, [GA4] Known bot traffic exclusion, Analytics Help, accessed 23 November 2026, https://support.google.com/analytics/answer/9888366

  7. 7.

    Google, [GA4] Filter out internal traffic, Analytics Help, accessed 23 November 2026, https://support.google.com/analytics/answer/10104470

  8. 8.

    Google, [GA4] Data filters, Analytics Help, accessed 23 November 2026, https://support.google.com/analytics/answer/10108813

  9. 9.

    Solidus, core/db/migrate/20160101010000_solidus_one_four.rb (table definitions for spree_orders, spree_payments, spree_refunds, spree_reimbursements, spree_return_items), GitHub, solidusio/solidus, https://github.com/solidusio/solidus/blob/main/core/db/migrate/20160101010000_solidus_one_four.rb

  10. 10.

    HM Revenue and Customs, Find out about changes to VAT legislation on face value vouchers (VAT Information Sheet 09/18), GOV.UK, https://www.gov.uk/guidance/find-out-about-changes-to-vat-legislation-on-face-value-vouchers-vat-information-sheet-0918

  11. 11.

    Ruby on Rails Guides, Configuring Rails Applications, config.active_record.default_timezone (default :utc), https://guides.rubyonrails.org/configuring.html

  12. 12.

    Ruby on Rails Guides, Active Record and PostgreSQL, section Timestamps (timestamp without time zone by default, datetime_type to change it), https://guides.rubyonrails.org/active_record_postgresql.html

  13. 13.

    GOV.UK, When do the clocks change?, accessed 23 November 2026, https://www.gov.uk/when-do-the-clocks-change

  14. 14.

    PostgreSQL Global Development Group, PostgreSQL documentation, Date/Time Functions and Operators, AT TIME ZONE, https://www.postgresql.org/docs/current/functions-datetime.html

  15. 15.

    Google, [GA4] BigQuery Export schema (event_date in the property's time zone, event_timestamp in microseconds UTC), Analytics Help, https://support.google.com/analytics/answer/7029846

  16. 16.

    dbt Labs, About microbatch incremental models (event_time, batch_size, lookback, unique_key on dbt-postgres, time zones), dbt Developer Hub, accessed 23 November 2026, https://docs.getdbt.com/docs/build/incremental-microbatch

  17. 17.

    Google Cloud, BigQuery documentation, Date functions, DATE, https://cloud.google.com/bigquery/docs/reference/standard-sql/date_functions

  18. 18.

    Tyler Akidau, Robert Bradshaw, Craig Chambers, Slava Chernyak, Rafael J. Fernández Moctezuma, Reuven Lax, Sam McVeety, Daniel Mills, Frances Perry, Eric Schmidt and Sam Whittle, The Dataflow Model: A Practical Approach to Balancing Correctness, Latency, and Cost in Massive Scale, Unbounded, Out of Order Data Processing, Proceedings of the VLDB Endowment, volume 8, number 12, 2015, https://www.vldb.org/pvldb/vol8/p1792-Akidau.pdf

  19. 19.

    The Consumer Contracts (Information, Cancellation and Additional Charges) Regulations 2013, SI 2013/3134, regulation 30, legislation.gov.uk, https://www.legislation.gov.uk/uksi/2013/3134/regulation/30

  20. 20.

    The Consumer Contracts (Information, Cancellation and Additional Charges) Regulations 2013, SI 2013/3134, regulation 35, legislation.gov.uk, https://www.legislation.gov.uk/uksi/2013/3134/regulation/35

  21. 21.

    The Consumer Contracts (Information, Cancellation and Additional Charges) Regulations 2013, SI 2013/3134, regulation 34, legislation.gov.uk, https://www.legislation.gov.uk/uksi/2013/3134/regulation/34

  22. 22.

    Google, [GA4] BigQuery Export (daily tables updated with late events), Analytics Help, https://support.google.com/analytics/answer/9358801

  23. 23.

    Solidus, core/app/models/spree/order_cancellations.rb (short_ship and cancel_unit on completed orders), GitHub, solidusio/solidus, https://github.com/solidusio/solidus/blob/main/core/app/models/spree/order_cancellations.rb

  24. 24.
  25. 25.

    dbt Labs, meta (resource config, moved under config in v1.10), dbt Developer Hub, https://docs.getdbt.com/reference/resource-configs/meta

  26. 26.

    dbt Labs, Unit tests (available from dbt v1.8), dbt Developer Hub, https://docs.getdbt.com/docs/build/unit-tests

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.