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.
| Task | How it is done today | Hours a month |
|---|---|---|
| Shipping labels | Copy each address into the carrier's website, print, stick | 82.5 |
| Returns | Read the email, check the order, send a label, inspect, refund by hand | 44.5 |
| Stock checks and purchase orders | Walk the shelves, compare with a spreadsheet, email suppliers | 24.0 |
| "Where is my order?" replies | Look up the order, look up the carrier, type a reply | 21.7 |
| Bookkeeping | Type daily sales, fees and refunds into the accounts | 20.0 |
| Receiving deliveries | Count, compare with the purchase order, update stock | 16.0 |
| Checking risky orders | Look at large first orders before shipping | 10.0 |
| Invoices for trade customers | Write 60 invoices in a word processor | 6.0 |
| Total | 224.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:
- Payment confirmed. The payment provider says yes.
- Risk check. Is this order worth a second look before anything ships?
- Stock allocated. The items are reserved in a stock location.
- Pick and pack. Someone collects the items and boxes them.
- Label and tracking number. The carrier is told about the parcel and returns a label.
- Handover. The parcel leaves the building, and the order is marked shipped.
- Tracking. The carrier reports progress, and the customer hears about it.
- Delivered, and with luck the story ends here.
- Return and refund, for the orders that come back.
- 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.
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.
where is the reorder point in units, is the average daily demand in units, is the supplier's lead time in days (from sending the order to having the goods on the shelf), and 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:
where is the safety stock, is the service level factor from the normal distribution (1.65 for being in stock in about 95% of reorder cycles), is the standard deviation of daily demand, and 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 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 a day, with a standard deviation of . The pottery needs days from order to delivery. Priya wants to be in stock in about 95% of cycles, so .
Safety stock: , rounded up to 16 mugs.
Reorder point: 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 documented | How access works |
|---|---|---|
| Royal Mail, Click & Drop | A public API specification to import orders, retrieve them, generate labels, create manifests and handle returns11 | Through a Click & Drop account and an API key |
| DPD UK | An API used by integration platforms to create labels | Credentials issued by DPD UK to holders of a MyDPD account12 |
| Evri | Integrations exist through shipping platforms | Platforms list an Evri corporate account as the prerequisite13 |
| Multi carrier platforms | One API in front of many carriers. Sendcloud, for example, offers APIs for shipments, labels and returns and connects to more than 160 carriers across Europe14 | A 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. ShippingLabelis 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_locklocks 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_referenceandcreate_labelare 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_onanddiscard_onare 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 seconds before retry number , 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, 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: 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: 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: hours. After the tracking emails and the status page, Priya counts 90 a month, now answered with a macro in about three minutes: 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.
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 returns a month. By hand, each took about 15 minutes of reading, checking, labelling and refunding: 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: 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: 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:
where is the net sales without VAT, is the gross sales including VAT, and 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 orders at £72, so . For simplicity, assume every item carries the standard 20% rate (in reality children's goods or books would not).
- Net sales:
- VAT:
- Payment fees at about 1.7%:
- Expected payout:
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:
| Signal | Points |
|---|---|
| First order from this customer | 1 |
| Order value over £400 | 2 |
| Delivery address differs from billing address | 1 |
| Three or more failed payment attempts in the last hour | 3 |
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 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:
where is the monthly value in pounds, is the hours saved per month, is the cost of an hour of the people doing the task today, and 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:
where is the priority score in pounds a month per developer day, is the monthly value from the first formula, and is the estimated build effort in developer days. Both are simple ratios, explained in Foundations: ratios and rates. A higher means more value back sooner for the same effort.
Example: ranking the eight automations
Priya prices an hour of her staff's time at (an invented figure, wages plus on costs). Callum estimates the build days. The error costs are the ones from the sections above.
| Automation | Hours saved | Error cost | Value a month | Build days | Priority |
|---|---|---|---|---|---|
| Labels and tracking numbers | 71.5 | £280 | £1,567 | 6 | 261 |
| Reorder alerts | 18.0 | £695 | £1,019 | 4 | 255 |
| Risk checks | 7.0 | £240 | £366 | 3 | 122 |
| Tracking emails and status page | 17.2 | £0 | £310 | 3 | 103 |
| Returns portal and refunds | 29.7 | £150 | £685 | 8 | 86 |
| Daily accounting journal | 16.0 | £100 | £388 | 5 | 78 |
| Receiving by scanning | 6.0 | £60 | £168 | 4 | 42 |
| Trade invoices | 5.5 | £0 | £99 | 3 | 33 |
Two lines worked through. Labels: , and . 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 . Then and . Contribution per order is built up line by line in unit economics and contribution margin per order.
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.
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.