Which parts of running a shop can I automate, and how? Stock, fulfilment, returns and service on Rails

TL;DR

Difficulty: Intermediate

Automation means the shop does the routine work by itself and people only see the exceptions.

  • Write every process as a trigger, a rule, an action and a record.
  • Solidus and Rails already give you the parts: state machines, the event bus, background jobs, schedules, unique indexes and an audit trail.
  • Automate reorder alerts, carrier labels, tracking emails, returns and refunds, invoices, a daily accounting journal and risk checks.
  • Keep decisions that commit money with a person, as a short list.
  • Rank by value per developer day, with legal deadlines first. In the example, 224.7 hours of monthly operations work fall to 53.8.

Behind every online order sits a trail of routine work: stock, labels, tracking, returns, refunds, invoices and bookkeeping. Most of it follows rules the business already has, which means software can do it. This chapter maps that work for one example shop and shows, step by step and in Rails and Solidus code, how to automate it and what to tackle first.

Automation means the shop does the routine, and people handle the exceptions

Every online shop has two jobs. One is selling: the pages, the ads, the checkout. The other starts the moment a customer presses "pay": the stock goes down, a parcel gets packed, a label gets printed, a tracking email goes out, a return comes back, money goes back, an invoice and a bookkeeping entry get written. Nobody sees the second job, and in a growing shop it quietly eats the week.

This chapter answers one question: which parts of running a shop can I automate, and how? My answer has one rule at its heart. Automation means the shop does the routine work by itself, and people only see the exceptions. A good automated process is not a robot that never needs a human. It is a process that handles the 95 cases that look the same, and puts the five odd ones in front of a person with everything they need to decide.

Every automated process has the same four parts:

  • a trigger, something that happened (an order was paid, a parcel was scanned, the clock struck six)
  • a rule, the decision the business would make anyway (if the stock falls below the reorder point, suggest a purchase)
  • an action, the work itself (create the label, send the email, write the credit note)
  • a record, a trace of what was done, when and why, so anyone can check it later.

If you can write a process down as those four parts, a computer can run it. If you cannot, the process is not ready for automation, and the first job is to agree how the business actually wants it done.

This chapter builds on one coherent system, which explains why the shop, its stock, its orders and its customers belong in one application and one database. Here I take that application and put it to work, on Ruby on Rails 8 and Solidus, the open source shop framework I build on. The code examples are short and every one is explained in plain words, so a shop owner can skip the code and still follow.

Example: where Wrenfield Home's month goes

Wrenfield Home is the invented homeware shop this series follows: ceramics, kitchen textiles, lamps and small furniture, about 1,400 products, sold from Leeds at wrenfieldhome.example. Priya owns it, Callum is the developer. The shop's baseline figures (all invented for the example): 1,980 orders a month at an average of £72, a return rate of 9% of orders, fulfilment at £6.50 per order and a return costing £9 to handle.

Priya and her two staff log a typical month of operations work. These hours are the example's, not a benchmark.

TaskHow it is done todayHours a month
Shipping labelsCopy each address into the carrier's website, print, stick82.5
ReturnsRead the email, check the order, send a label, inspect, refund by hand44.5
Stock checks and purchase ordersWalk the shelves, compare with a spreadsheet, email suppliers24.0
"Where is my order?" repliesLook up the order, look up the carrier, type a reply21.7
BookkeepingType daily sales, fees and refunds into the accounts20.0
Receiving deliveriesCount, compare with the purchase order, update stock16.0
Checking risky ordersLook at large first orders before shipping10.0
Invoices for trade customersWrite 60 invoices in a word processor6.0
Total224.7

That is about 1.3 full time people doing work the shop's own data already knows how to do. The rest of this chapter goes through each line, shows what the automated version looks like, and ends with a way to decide which line to tackle first.

The operations map: everything that happens after "pay"

Before automating anything, draw the whole path one order takes. I call it the operations map. For a homeware shop it has ten stops:

  1. Payment confirmed. The payment provider says yes.
  2. Risk check. Is this order worth a second look before anything ships?
  3. Stock allocated. The items are reserved in a stock location.
  4. Pick and pack. Someone collects the items and boxes them.
  5. Label and tracking number. The carrier is told about the parcel and returns a label.
  6. Handover. The parcel leaves the building, and the order is marked shipped.
  7. Tracking. The carrier reports progress, and the customer hears about it.
  8. Delivered, and with luck the story ends here.
  9. Return and refund, for the orders that come back.
  10. Invoice and bookkeeping, which follow every money movement.

Underneath runs a second loop: stock falls, a reorder point is reached, a purchase order goes out, goods arrive, stock rises.

Tap or click to open full screen and move around

Example: one lamp and two mugs, traced through the map

A customer in Bristol orders a brass table lamp and two stoneware mugs at 9.14am, paying by card. In Wrenfield's automated shop, this is what happens, and who touches it:

  • 9.14am: the payment is confirmed and the order completes. The shop scores the order for risk. It is the customer's third order, the billing and delivery addresses match, the value is £118. Score zero, no review.
  • 9.14am: the stock for the lamp and the mugs is allocated from the Leeds warehouse. The order joins the 11am pick list.
  • 9.15am: a background job asks the carrier for a label. The tracking number comes back and is stored on the shipment.
  • 11.40am: a packer picks the three items, packs them, prints the stored label and scans the parcel at the dispatch bench. The scan marks the shipment as shipped, which sends the "your order is on its way" email with the tracking link.
  • Next day: the carrier's status updates are pulled in, the customer gets a "delivered" email in the afternoon.

The only human work was picking and packing, about four minutes. Nobody typed an address, looked up a tracking number or wrote an email. That is the target state for the routine case.

The building blocks Solidus and Rails already give you

You do not build this from scratch. A Solidus shop on Rails 8 already contains the pieces, and knowing them saves weeks.

State machines: every order, payment, shipment and return knows where it is

A state machine is a list of the states a thing can be in, plus the allowed moves between them. Solidus models orders, payments, shipments and returned items this way. A shipment, for example, starts as pending, becomes ready when it can go, then shipped, or canceled1. A payment moves through states such as checkout, processing, pending, completed, failed and void2. A returned item carries two of them: a reception status (is it awaiting, received, lost_in_transit, and so on) and an acceptance status (pending, accepted, rejected or manual_intervention_required)3 4.

Why this matters for automation: a state is a trigger you can trust. "Every shipment that is ready and has no label" is a precise, queryable list. A spreadsheet column called "status" that three people edit by hand is not.

Example: the morning list

At 8am Callum runs one query: shipments in state ready with no stored label. It returns 14. Each of those 14 is a parcel that should have had a label overnight and did not, so each one is a real problem (a carrier outage, an address the carrier rejected). Without states, finding those 14 among 66 daily orders means opening every order.

The event bus: let the shop announce what happened

Solidus has a built in publish and subscribe system called the event bus, Spree::Bus. When something important happens, the core publishes an event, and any code you write can subscribe to it. Solidus registers eight events out of the box: order_finalized, order_canceled, order_emptied, order_recalculated, order_short_shipped, carton_shipped, reimbursement_reimbursed and reimbursement_errored5. The Solidus guides show a subscriber as a small Ruby class that names the event and the method to run6.

The guides also draw a useful line: a subscriber is for work that follows an event (send a message, collect stats, start a job), never for logic that should be able to stop the order from completing6. That is exactly the shape of most operations automation.

Example: one subscriber, three jobs

When an order completes, Wrenfield's shop needs to do three independent things: score the order for risk, request labels, and update the stock forecast. One subscriber hands each to a background job:

# app/subscribers/operations_subscriber.rb
class OperationsSubscriber
  include Omnes::Subscriber

  handle :order_finalized, with: :start_operations, id: :wrenfield_operations

  def start_operations(event)
    order = event.payload[:order]
    RiskScoreJob.perform_later(order.id)
    order.shipments.each { |shipment| CreateShippingLabelJob.perform_later(shipment.id) }
    DemandSnapshotJob.perform_later(order.id)
  end
end

# config/initializers/operations_subscriber.rb
Rails.application.config.to_prepare do
  OperationsSubscriber.new.subscribe_to(Spree::Bus)
end

The subscriber only enqueues work, so the customer's checkout never waits for a carrier or a calculation. The registration in to_prepare follows the pattern in the Solidus guides6.

Background jobs and schedules

A background job is a piece of work the application does outside the customer's request, in a separate worker process. Rails 8 ships Solid Queue for this, which keeps the queue in the database. Solid Queue also runs recurring tasks, jobs that start on a schedule like a cron entry, defined in config/recurring.yml with a job class and a schedule such as "every day at 9am"7. I covered how to design jobs that do not take each other down in background workers in Rails, so here I only use them.

Example: the daily schedule

# config/recurring.yml
production:
  reorder_alerts:
    class: ReorderAlertJob
    schedule: every day at 6am
  missing_labels_sweep:
    class: MissingLabelSweepJob
    schedule: every 15 minutes
  tracking_refresh:
    class: TrackingRefreshJob
    schedule: every hour
  daily_journal:
    class: DailyJournalJob
    schedule: every day at 2am

Four lines of configuration replace four things someone used to remember to do. The sweep every 15 minutes is the safety net: anything the event driven path missed gets picked up within a quarter of an hour.

Idempotency: doing it twice must be harmless

Idempotent means that running something twice has the same effect as running it once. Jobs get retried, networks time out, a worker restarts halfway through. If "create a label" is not idempotent, a retry buys a second label and you pay twice. Payment providers build this in. Stripe, for example, accepts an idempotency key with each request, saves the result of the first request made with that key and returns the saved result to any retry with the same key8. Your own jobs need the same property, and in a Rails app the simplest tool is a database unique index: the second attempt to create the same record fails loudly instead of creating a duplicate.

Example: the label that was almost bought twice

Callum's label job calls the carrier, the carrier creates the label, and the response times out on the way back. The job is retried. Without a guard, the retry buys a second label: a few pounds wasted and, worse, two tracking numbers for one parcel, one of which will never move. With a shipping_labels table that has a unique index on shipment_id, and a job that checks whether its label is already stored before calling the carrier, the retry finds the stored result and stops. Where the carrier lets you look a shipment up by your own reference, the job asks the carrier first, which closes the last gap: the label created during the timeout.

Audit trail: who did what, and when

An audit trail is the record part of every process. Recent Solidus versions record state changes of orders, payments and shipments as Spree::StateChange rows, with the previous and the new state, written by a background job after each change9. For your own automation, add a plain table of events: what the automation did, to which record, with what input and result. It costs almost nothing and it answers the question every shop owner asks the day something goes wrong: "did the system do this, or did someone?"

Example: the disputed refund

A customer says a refund never arrived. Priya opens the order and sees the return item move from awaiting to received on 3 March at 10.12am, the reimbursement performed at 10.13am by the returns automation, and the payment provider's refund reference. The dispute takes two minutes instead of an afternoon of searching emails.

Stock and reordering: let the numbers say when to buy

Running out of a best seller costs sales. Over ordering ties up cash and shelf space. The middle path is a reorder point: the stock level at which you order more, set so that new stock arrives before the old runs out.

The reorder point has two parts. The first covers the expected demand while you wait for the supplier. The second, the safety stock, covers the days when demand runs higher than average.

R=dˉ×L+SR = \bar{d} \times L + S

where RR is the reorder point in units, dˉ\bar{d} is the average daily demand in units, LL is the supplier's lead time in days (from sending the order to having the goods on the shelf), and SS is the safety stock in units. The average is explained in Foundations: mean.

A common way to size the safety stock, when daily demand varies but the lead time is reliable, is:

S=z×σd×LS = z \times \sigma_d \times \sqrt{L}

where SS is the safety stock, zz is the service level factor from the normal distribution (1.65 for being in stock in about 95% of reorder cycles), σd\sigma_d is the standard deviation of daily demand, and LL is the lead time in days. The square root appears because the day to day ups and downs partly cancel out over a longer wait. Standard deviation is explained in Foundations: spread and the normal distribution in Foundations: distributions. The forecasting chapter, forecasting in eCommerce, goes much further: seasonal demand, uncertain lead times and how to forecast dˉ\bar{d} properly. Here the point is that once the numbers exist, the shop can watch them every morning.

Example: the sage stoneware mug

Wrenfield's sage stoneware mug sells on average dˉ=6\bar{d} = 6 a day, with a standard deviation of σd=2.5\sigma_d = 2.5. The pottery needs L=14L = 14 days from order to delivery. Priya wants to be in stock in about 95% of cycles, so z=1.65z = 1.65.

Safety stock: S=1.65×2.5×14=1.65×2.5×3.742=15.4S = 1.65 \times 2.5 \times \sqrt{14} = 1.65 \times 2.5 \times 3.742 = 15.4, rounded up to 16 mugs.

Reorder point: R=6×14+16=84+16=100R = 6 \times 14 + 16 = 84 + 16 = 100 mugs.

On Tuesday morning there are 112 mugs on the shelf and none on order, so nothing happens. By Wednesday morning 14 more have sold and 98 are left. That is at or below 100, so the shop suggests a purchase order of 180 mugs, which is 30 days of average demand.

The reorder alert job

Solidus keeps stock per variant (a product in one size or colour) and per stock location in Spree::StockItem, with a count_on_hand column. It has no built in reorder point, so Callum adds a small table of his own: one reorder rule per variant, with the reorder point and the order quantity.

# app/jobs/reorder_alert_job.rb
class ReorderAlertJob < ApplicationJob
  queue_as :operations

  def perform
    ReorderRule.active.includes(:variant).find_each do |rule|
      on_hand  = Spree::StockItem.where(variant_id: rule.variant_id).sum(:count_on_hand)
      on_order = rule.open_purchase_quantity  # units already ordered, not yet received
      next if on_hand + on_order > rule.reorder_point

      # One open suggestion per variant: a unique index makes a second run harmless
      PurchaseSuggestion.find_or_create_by!(variant_id: rule.variant_id, status: "open") do |s|
        s.quantity = rule.order_quantity
        s.supplier_id = rule.supplier_id
      end
    end
  end
end

In plain words: every morning, for every product with a rule, add up the stock in all locations and what is already on order. If that total is at or below the reorder point, open a purchase suggestion, unless one is already open. Counting what is already on order matters: without it the job would suggest the same 180 mugs again every morning until they arrive.

Notice what the job does not do. It does not send the order to the supplier. It suggests, and Priya approves the suggestions in one list each morning, because a purchase commits money and she may know something the numbers do not (a supplier closing for a holiday, a product she plans to drop). That is the rule from the start of the chapter: the routine is automatic, the decision stays with a person, and the person sees a short list instead of 1,400 products.

Purchasing and receiving: close the loop

Once Priya approves the suggestions, the shop turns them into purchase orders grouped by supplier and sends each supplier one email with a PDF and a CSV attached, or posts the order into the supplier's own system where one exists. The purchase order carries Wrenfield's order number, so the delivery note that comes back can be matched to it.

Receiving is where stock records usually drift away from reality. The automated version is a scanning screen at the goods in bench: scan the purchase order, scan each item, enter the count, flag anything damaged. When the delivery is booked in, the shop writes a stock movement for each line. In Solidus a Spree::StockMovement belongs to a stock item, has a quantity, and can point to the thing that caused it, its originator10. Using the purchase order as the originator means every unit of stock can be traced back to the delivery it came from.

# app/services/receive_delivery.rb
class ReceiveDelivery
  def call(purchase_order, counted:, location:)
    Spree::StockMovement.transaction do
      counted.each do |variant_id, quantity|
        item = location.stock_items.find_by!(variant_id: variant_id)
        Spree::StockMovement.create!(stock_item: item, quantity: quantity, originator: purchase_order)
      end
      purchase_order.update!(status: "received", received_at: Time.current)
    end
  end
end

The transaction makes the delivery all or nothing: either every line is booked and the purchase order is closed, or nothing changes. Chapter two explains why that matters in one coherent system.

Example: 180 mugs, four broken

The pottery delivers 180 sage mugs. The receiver scans them, counts 176 whole and four broken, and photographs the broken ones. The shop books 176 into stock, closes the purchase order line with a shortfall of four, and creates a supplier claim with the photos attached. Before, the receiver would have written "4 broken" on the delivery note, and the claim depended on someone remembering to send it. Now the claim exists the moment the delivery is booked, and a weekly list shows every open claim and its value: four mugs at a cost of £6.20 each is £24.80 the pottery owes.

Labels, tracking numbers and the carrier's API

The single biggest line in Wrenfield's month is typing addresses into a carrier's website. It is also the easiest to remove, because carriers want you to send them data rather than paper.

An API (application programming interface) is a documented door through which one piece of software talks to another. A carrier's shipping API takes the parcel's details (address, weight, service) and returns a label and a tracking number. What is available depends on the carrier and on your contract:

Carrier (UK)What is documentedHow access works
Royal Mail, Click & DropA public API specification to import orders, retrieve them, generate labels, create manifests and handle returns11Through a Click & Drop account and an API key
DPD UKAn API used by integration platforms to create labelsCredentials issued by DPD UK to holders of a MyDPD account12
EvriIntegrations exist through shipping platformsPlatforms list an Evri corporate account as the prerequisite13
Multi carrier platformsOne API in front of many carriers. Sendcloud, for example, offers APIs for shipments, labels and returns and connects to more than 160 carriers across Europe14A platform subscription, plus your own carrier contracts where needed

A multi carrier platform costs a fee but saves writing and maintaining one integration per carrier. For a shop with two carriers, a direct integration is usually manageable. For a shop that ships with five, the platform often wins. Either way, the shop's own code stays the same shape: a gateway class per carrier behind one interface, so the label job does not care which carrier is underneath.

The shipment label job with retries

# app/jobs/create_shipping_label_job.rb
class CreateShippingLabelJob < ApplicationJob
  queue_as :fulfilment

  # Network trouble or a carrier outage: try again, waiting longer each time
  retry_on Carriers::TemporaryError, wait: :polynomially_longer, attempts: 8

  # The carrier rejected the data (a bad postcode, an overweight parcel): a person must look
  discard_on Carriers::RejectedError do |job, error|
    FulfilmentIssue.create!(shipment_id: job.arguments.first, reason: error.message)
  end

  def perform(shipment_id)
    shipment = Spree::Shipment.find(shipment_id)
    return unless shipment.ready?
    return if RiskReview.open.exists?(order_id: shipment.order_id)

    label = ShippingLabel.find_or_create_by!(shipment_id: shipment.id)  # unique index on shipment_id
    label.with_lock do
      purchase(label, shipment) unless label.purchased?
    end
  end

  private

  def purchase(label, shipment)
    gateway = CarrierGateway.for(shipment)
    result  = gateway.find_by_reference(shipment.number) || gateway.create_label(shipment)
    label.update!(tracking_number: result.tracking_number,
                  carrier_reference: result.reference,
                  label_pdf: result.pdf,
                  purchased_at: Time.current)
  end
end

Line by line, for the beginner:

  • The job only acts on shipments that are ready, and it skips any order with an open risk review, so a held order never gets a label.
  • ShippingLabel is Wrenfield's own table, one row per shipment. The unique index means a second job for the same shipment can never create a second row.
  • with_lock locks that row while the job works, so two workers cannot buy the label at the same moment.
  • The gateway first asks the carrier whether a label already exists for this shipment number, and only creates one if not. CarrierGateway, find_by_reference and create_label are Wrenfield's own wrapper, not a carrier's method names. Inside it, each carrier's real API is called. If a carrier offers no lookup by reference, the wrapper returns nothing and the stored row is the only guard.
  • retry_on and discard_on are Active Job's built in error handling15. Temporary errors are retried. Rejections are not, because sending the same bad postcode eight times will not fix it. They go to a list of fulfilment issues for a person.

The label is created when the order is paid, but the order is only marked as shipped when the packed parcel is scanned at dispatch. In Solidus, that scan calls order.shipping.ship_shipment(shipment, tracking_number: label.tracking_number). That method marks the items as shipped, records a carton with the tracking number and publishes the carton_shipped event16, and Solidus's own subscriber sends the shipped email from that event.

Example: what the retry schedule means

With wait: :polynomially_longer, Active Job waits roughly n4+2n^4 + 2 seconds before retry number nn, plus a small random jitter15. With attempts: 8 there is the first try and seven retries, so the waits are 3, 18, 83, 258, 627, 1,298 and 2,403 seconds. Added up, 3+18+83+258+627+1,298+2,403=4,6903 + 18 + 83 + 258 + 627 + 1{,}298 + 2{,}403 = 4{,}690 seconds, about 78 minutes. A carrier outage of up to an hour heals itself. Anything longer ends as a fulfilment issue, which is right: by then a person should know.

Example: the hours

Typing a label used to take Wrenfield about 2.5 minutes per order: 1,980×2.5=4,9501{,}980 \times 2.5 = 4{,}950 minutes, 82.5 hours a month. With labels created automatically, the remaining work is checking the morning list of fulfilment issues and printing, about 20 seconds per order on average: 1,980×20/3,600=111{,}980 \times 20 / 3{,}600 = 11 hours. The saving is 71.5 hours a month. There is a quality gain too. Priya estimates that about 1% of hand typed labels had an error that sent a parcel astray, around 20 parcels a month, each costing roughly £14 to reship. That is £280 a month in errors that copying the address the customer typed removes.

Tracking and "where is my order?"

Most "where is my order?" messages are not complaints. They are customers who do not know something the shop already knows. Automation here has two halves.

Tell the customer before they ask. Pull each open shipment's status from the carrier's tracking API on a schedule, or receive it by push where the carrier offers it. Store each status change. Send an email at the moments that matter: shipped, out for delivery, delivered, and "delayed" if a parcel has not moved for two working days. Keep the emails plain and useful. What comes after delivery is covered in after the purchase.

Give the customer a page instead of an inbox. An order status page that takes the order number and the email address, and shows the order's real state, the tracking events and the expected date. No login needed, because the combination of order number and email is enough to prove it is their order.

For the messages that still arrive, customer service gets macros: reply templates that pull the order's data in automatically ("Your order WH184233 left our Leeds warehouse on Monday with Royal Mail, tracking number ..."). The person reads, checks, sends.

Example: the enquiries that stopped

Wrenfield received about 260 "where is my order?" messages a month, at about five minutes each: 260×5/60=21.7260 \times 5 / 60 = 21.7 hours. After the tracking emails and the status page, Priya counts 90 a month, now answered with a macro in about three minutes: 90×3/60=4.590 \times 3 / 60 = 4.5 hours. The saving, 17.2 hours a month, comes almost entirely from messages that were never sent. Both counts are the example's invented figures.

Returns: a portal, an inspection and a refund on time

Returns cost twice: once in handling, once in margin. The returns chapter measures that cost. Here the job is to make each return quick to process and fair to the customer.

The automated returns flow in Solidus maps onto models that already exist. A customer asks to return items from an order, which creates a Spree::ReturnAuthorization with one return item per unit and a reason. When the parcel arrives, the warehouse books it as a customer return, and each return item moves from awaiting to received3. The acceptance status then decides what happens: accepted items can be reimbursed, rejected ones go back to the customer or are refused, and anything odd lands in manual_intervention_required for a person4. A Spree::Reimbursement built from the accepted items performs the refund, and publishes reimbursement_reimbursed when it succeeds or reimbursement_errored when it does not17.

Tap or click to open full screen and move around

The deadline the automation must keep

The law sets a clock. Under the Consumer Contracts Regulations 2013, when a consumer cancels a distance sale of goods, the trader must refund without undue delay, and at the latest 14 days after the day it receives the goods back or, if earlier, the day the consumer supplies evidence of having sent them back (unless the trader offered to collect them). The refund uses the same means of payment unless the consumer agreed otherwise, and the standard delivery charge is refunded too18. This is general information, not legal advice, and your own terms and situation may add detail.

An automated flow makes the deadline visible. Every received return item gets a due date, and a daily job lists any return that is received and not yet reimbursed with fewer than three days left. A person sees that list long before it becomes a breach.

# app/subscribers/returns_subscriber.rb
class ReturnsSubscriber
  include Omnes::Subscriber

  handle :reimbursement_reimbursed, with: :write_credit_note, id: :wrenfield_credit_note
  handle :reimbursement_errored,    with: :flag_for_review,   id: :wrenfield_refund_failed

  def write_credit_note(event)
    CreditNoteJob.perform_later(event.payload[:reimbursement].id)
  end

  def flag_for_review(event)
    reimbursement = event.payload[:reimbursement]
    FulfilmentIssue.create!(order_id: reimbursement.order_id, reason: "Refund failed, check the payment")
  end
end

The successful refund writes a credit note, the failed one becomes a task for a person. The money never moves without a document, and a failure never disappears into a log file.

Example: 178 returns a month

With a 9% return rate on 1,980 orders, Wrenfield handles 1,980×0.09=1781{,}980 \times 0.09 = 178 returns a month. By hand, each took about 15 minutes of reading, checking, labelling and refunding: 178×15/60=44.5178 \times 15 / 60 = 44.5 hours. With the portal creating the authorisation and the label, and the inspection screen triggering the refund, the remaining human work is the inspection itself and the odd cases, about five minutes each: 178×5/60=14.8178 \times 5 / 60 = 14.8 hours. The saving is 29.7 hours. Priya also counts about six late or wrong refunds a month under the old process, each costing roughly £25 in goodwill vouchers and extra messages, so £150 a month.

Invoices, credit notes and e invoicing

Every order needs a document, every refund needs a credit note, and both must match the accounts. Generating them is the simplest automation in this chapter: when order_finalized fires, a job renders the invoice from the order's own data and stores it, and when a reimbursement succeeds, the subscriber above writes the credit note. Numbering comes from a database sequence, so there are no gaps and no duplicates.

What is changing is the format. An e invoice is not a PDF sent by email. It is an invoice in a structured data format that the recipient's software can read without a person typing it in. The UK government announced at Budget 2025 that VAT invoices will have to be issued as e invoices from April 2029, and has published an implementation roadmap for VAT registered businesses from 1 April 202919. For a shop selling mostly to consumers, the obligation will matter for its business customers, such as cafés and hotels buying tableware in bulk.

If you sell to businesses in Germany or Ireland, their rules apply to your customers there. The German and Irish editions of this chapter cover those. The B2B side of Solidus itself (price lists, quotes, payment terms) is in B2B eCommerce on Solidus.

The automation advantage of owning the code shows here. The invoice data already lives in the shop's database, line by line, with VAT rates and customer details. Producing a structured format is one more renderer next to the PDF renderer, not a migration project.

Example: 60 trade invoices

Wrenfield's trade customers place about 60 orders a month. Writing each invoice by hand took six minutes: 60×6/60=660 \times 6 / 60 = 6 hours a month. Generated automatically, the remaining work is a quick check of the monthly list, about half an hour. The saving is small, 5.5 hours, but the invoice now has the same number, date and amounts as the order and the accounts, with no retyping in between.

Accounting exports: one journal a day, reconciled

Bookkeeping by retyping is slow and error prone, and it gets worse with volume. The automated version does not send every order to the accounting software. It sends one daily journal: the day's sales split by VAT rate, the payment fees, the refunds, and the amount the payment provider will pay out. Accountants generally prefer a clean daily summary to thousands of individual entries, and the summary can always be traced back to the orders in the shop.

The numbers in the journal follow one formula. Prices in the shop include VAT, so the net amount is:

N=G1+vN = \frac{G}{1 + v}

where NN is the net sales without VAT, GG is the gross sales including VAT, and vv is the VAT rate as a decimal (0.20 for 20%). How percentages turn into decimals is in Foundations: percentages.

Xero, for example, publishes an accounting API that covers invoices, payments, bank transactions, contacts and credit notes20, so a nightly job can post the journal directly. If your accountant works in another package, agree the import format with them and generate exactly that file.

Example: the journal for one Tuesday

On an average day Wrenfield takes 1,980/30=661{,}980 / 30 = 66 orders at £72, so G=66×72=£4,752G = 66 \times 72 = £4{,}752. For simplicity, assume every item carries the standard 20% rate (in reality children's goods or books would not).

  • Net sales: N=4,752/1.20=£3,960.00N = 4{,}752 / 1.20 = £3{,}960.00
  • VAT: 4,752−3,960=£792.004{,}752 - 3{,}960 = £792.00
  • Payment fees at about 1.7%: 4,752×0.017=£80.784{,}752 \times 0.017 = £80.78
  • Expected payout: 4,752−80.78=£4,671.224{,}752 - 80.78 = £4{,}671.22

The job posts these four lines with the date and a reference to the day. When the payout lands in the bank, the bank feed matches it to £4,671.22, and any difference shows up at once instead of at the year end. Priya estimates bookkeeping fell from 20 hours to four a month, and the accountant's correction time, about £100 a month, went away.

Risk checks: rules first, people for the edge cases

Payment providers screen card payments for fraud. What they cannot see is what only your shop knows: that this is a first order, that the delivery address is a parcel locker three counties away from the billing address, that the same email tried four cards in ten minutes. A small rule based score, run on order_finalized, adds that knowledge.

Example: scoring two orders

Wrenfield's rules (invented for the example) give points:

SignalPoints
First order from this customer1
Order value over £4002
Delivery address differs from billing address1
Three or more failed payment attempts in the last hour3

An order with four points or more is held for review. The lamp and mugs order from earlier scores zero: a returning customer, £118, matching addresses. A £640 oak sideboard ordered as a first order, to a different address, after three declined cards, scores 1+2+1+3=71 + 2 + 1 + 3 = 7 and is held. The label job skips it, because it checks for an open review. Priya sees the order with the customer's history, the payment attempts and the addresses on one screen and decides in a minute. Two avoided chargebacks a month at about £120 each is £240, and the review time fell from ten hours to three because nobody looks at the 1,960 ordinary orders any more.

What to automate first: rank by value per day of work

Everything above is possible. Not everything is worth doing first. I rank candidate automations by how much they return each month for each day of building.

The monthly value of automating a task is:

V=h×w+eV = h \times w + e

where VV is the monthly value in pounds, hh is the hours saved per month, ww is the cost of an hour of the people doing the task today, and ee is the monthly cost of the errors the automation removes, an expected cost as in Foundations: expected value. The priority is the value per day of development:

P=VDP = \frac{V}{D}

where PP is the priority score in pounds a month per developer day, VV is the monthly value from the first formula, and DD is the estimated build effort in developer days. Both are simple ratios, explained in Foundations: ratios and rates. A higher PP means more value back sooner for the same effort.

Example: ranking the eight automations

Priya prices an hour of her staff's time at w=£18w = £18 (an invented figure, wages plus on costs). Callum estimates the build days. The error costs are the ones from the sections above.

AutomationHours saved hhError cost eeValue VV a monthBuild days DDPriority PP
Labels and tracking numbers71.5£280£1,5676261
Reorder alerts18.0£695£1,0194255
Risk checks7.0£240£3663122
Tracking emails and status page17.2£0£3103103
Returns portal and refunds29.7£150£685886
Daily accounting journal16.0£100£388578
Receiving by scanning6.0£60£168442
Trade invoices5.5£0£99333

Two lines worked through. Labels: V=71.5×18+280=1,287+280=£1,567V = 71.5 \times 18 + 280 = 1{,}287 + 280 = £1{,}567, and P=1,567/6=261P = 1{,}567 / 6 = 261. Reorder alerts: the error cost is lost sales, about 35 orders a month that found a best seller out of stock, at Wrenfield's contribution of £19.86 per order, so e=35×19.86=£695e = 35 \times 19.86 = £695. Then V=18×18+695=324+695=£1,019V = 18 \times 18 + 695 = 324 + 695 = £1{,}019 and P=1,019/4=255P = 1{,}019 / 4 = 255. Contribution per order is built up line by line in unit economics and contribution margin per order.

Example figures. Monthly value per developer day of building, in pounds. Labels and tracking numbers 261, reorder alerts 255, risk checks 122, tracking emails and status page 103, returns portal and refunds 86, daily accounting journal 78, receiving by scanning 42, trade invoices 33. Tap or click to open full screen and move around

Three things the ranking does not capture, so add them by judgement:

  • Legal deadlines beat the score. If a law makes e invoicing compulsory for your customers by a date, that line moves up whatever its score.
  • Dependencies. The returns portal needs the label integration, so labels come first anyway.
  • Measure after you build. The hours in the table are estimates. A month after each automation goes live, count again. If the saving is half the estimate, find out why before building the next one. Measuring the value of each part of the shop properly is the subject of what is each part of your shop worth.

Example: the month after

With all eight automations live, Wrenfield's operations hours fall from 224.7 to 53.8 a month. The chart compares each task before and after.

Example figures. Hours a month per task before and after automation. Labels 82.5 to 11. Returns 44.5 to 14.8. Stock and purchasing 24 to 6. Where is my order replies 21.7 to 4.5. Bookkeeping 20 to 4. Receiving 16 to 10. Risk checks 10 to 3. Trade invoices 6 to 0.5. Total 224.7 to 53.8. Tap or click to open full screen and move around

The 170.9 hours saved are not a headcount cut in Priya's plan. They are the time her team now spends on photography, product descriptions and customer conversations that the shop never had time for. And picking and packing, which no software removes, now runs without interruptions.

Why owning the system makes this easier

Rented platforms automate a great deal of this too, mostly through apps and built in workflow tools, and for a small shop with standard processes that can be enough. The fair comparison is in rented platform or your own system and where Rails and Solidus shine.

What owning the code changes is reach. Every process in this chapter reads and writes the same database: the label job checks the risk review, the returns flow writes the credit note, the reorder job counts open purchase orders. When the processes live in your own application, a new rule is a few lines of code and a test, not a search for an app that happens to connect the two things you need. And every automated step leaves data behind, which is what later chapters use to measure and forecast.

I build shops this way on Rails and Solidus, test first, with every release going through a test gate and a release register, and the code belongs to the client once paid. That last point matters for operations more than anywhere: the processes that run your business are written down in code you own, not in someone else's settings screen.

Conclusion

Automation is not about removing people. It is about the shop doing the routine work by itself, every time, and putting the exceptions in front of a person with what they need to decide.

Write each process as a trigger, a rule, an action and a record. Use what Solidus and Rails already give you: state machines for reliable triggers, the event bus to react to what happened, background jobs and schedules to do the work, unique indexes to make retries harmless, and an audit trail so every action can be explained. Start with the processes that return the most per day of work, which for most shops means labels and stock, then tracking, risk, returns and bookkeeping. Keep legal deadlines, such as the refund clock and e invoicing, ahead of the ranking. Then count the hours again, because the estimate is a hypothesis and the month after is the test.

Want to know which parts of your shop's operations could run by themselves? Book the free workshop and I will map your processes from payment to refund with you, and the first two weeks of work are on me.

Sources

  1. 1.

    Solidus, source of the shipment state machine, Spree::Core::StateMachines::Shipment, solidus_core on GitHub, main branch, checked 22 November 2026, https://github.com/solidusio/solidus/blob/main/core/app/models/spree/core/state_machines/shipment.rb

  2. 2.

    Solidus, source of the payment state machine, Spree::Core::StateMachines::Payment, solidus_core on GitHub, main branch, checked 22 November 2026, https://github.com/solidusio/solidus/blob/main/core/app/models/spree/core/state_machines/payment.rb

  3. 3.

    Solidus, source of the return item reception status state machine, solidus_core on GitHub, main branch, checked 22 November 2026, https://github.com/solidusio/solidus/blob/main/core/app/models/spree/core/state_machines/return_item/reception_status.rb

  4. 4.

    Solidus, source of the return item acceptance status state machine, solidus_core on GitHub, main branch, checked 22 November 2026, https://github.com/solidusio/solidus/blob/main/core/app/models/spree/core/state_machines/return_item/acceptance_status.rb

  5. 5.

    Solidus, source of the core engine, the events registered on Spree::Bus, solidus_core on GitHub, main branch, checked 22 November 2026, https://github.com/solidusio/solidus/blob/main/core/lib/spree/core/engine.rb

  6. 6.

    Solidus, Subscribing to events, Solidus Guides, checked 22 November 2026, https://guides.solidus.io/customization/subscribing-to-events

  7. 7.

    Rails, Solid Queue README, section Recurring tasks, GitHub, checked 22 November 2026, https://github.com/rails/solid_queue#recurring-tasks

  8. 8.

    Stripe, Idempotent requests, Stripe API reference, checked 22 November 2026, https://docs.stripe.com/api/idempotent_requests

  9. 9.

    Solidus, source of Spree::StateChangeTracking, solidus_core on GitHub, main branch, checked 22 November 2026, https://github.com/solidusio/solidus/blob/main/core/app/models/concerns/spree/state_change_tracking.rb

  10. 10.

    Solidus, source of Spree::StockMovement, solidus_core on GitHub, main branch, checked 22 November 2026, https://github.com/solidusio/solidus/blob/main/core/app/models/spree/stock_movement.rb

  11. 11.

    Royal Mail, ChannelShipper and Royal Mail Public API (Click and Drop API v1 specification), checked 22 November 2026, https://api.parcel.royalmail.com/doc/v1/click-and-drop-api-v1.yaml

  12. 12.

    AfterShip, DPD UK Developer Guide and API Credentials, AfterShip Help Center, checked 22 November 2026, https://support.aftership.com/en/shipping/articles/15380750-dpd-uk-developer-guide-and-api-credentials

  13. 13.

    ShipStation, EVRi guide, ShipStation API documentation, checked 22 November 2026, https://docs.shipstation.com/apis/shipengine/docs/carriers/evri-guide

  14. 14.

    Sendcloud, Introduction, Sendcloud developer documentation, checked 22 November 2026, https://sendcloud.dev/

  15. 15.

    Ruby on Rails API, ActiveJob::Exceptions::ClassMethods, retry_on and discard_on, checked 22 November 2026, https://api.rubyonrails.org/classes/ActiveJob/Exceptions/ClassMethods.html

  16. 16.

    Solidus, source of Spree::OrderShipping, methods ship_shipment and ship, solidus_core on GitHub, main branch, checked 22 November 2026, https://github.com/solidusio/solidus/blob/main/core/app/models/spree/order_shipping.rb

  17. 17.

    Solidus, source of Spree::Reimbursement, method perform!, solidus_core on GitHub, main branch, checked 22 November 2026, https://github.com/solidusio/solidus/blob/main/core/app/models/spree/reimbursement.rb

  18. 18.

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

  19. 19.

    HM Revenue and Customs, E invoicing requirements, policy paper, GOV.UK, checked 22 November 2026, https://www.gov.uk/government/publications/vat-electronic-invoicing/e-invoicing-requirements

  20. 20.

    Xero, Accounting API overview, Xero Developer, checked 22 November 2026, https://developer.xero.com/documentation/api/accounting/overview