I’ve been building Our Kev, a phone-first admin app for UK tradespeople: mileage, expenses and receipts, quotes, invoices, time on site, and a running CIS refund estimate for subcontractors. It’s Next.js 16, React 19 and Postgres, and the people using it are often stood in a loft with one bar of signal and a phone clock nobody has touched since 2019. This post is the code that deals with that: requests that wait for signal, timestamps from a phone you can’t fully trust, money without floats, the UK’s odd tax calendar, and reading receipts with Claude.
Holding taps until there’s signal
Next.js 16 has an experimental offline mode, switched on in next.config.ts:
const nextConfig: NextConfig = {
experimental: { useOffline: true },
}
When a server action, navigation or prefetch fails with a network error, Next holds it, polls the current URL with HEAD requests (500 ms, 1 s, 2 s, then every 3 s) and replays it once the network answers. From the component’s point of view, the server action’s promise just resolves late. No retry loops, no queue code, no “please try again” toasts.
The UI side is a banner that reads one hook:
'use client'
import { useOffline } from 'next/offline'
export function OfflineBanner() {
const offline = useOffline()
if (!offline) return null
return (
<div role="status">
No signal. Anything you tap is saved with the right time when signal
comes back. Keep Kev open until then.
</div>
)
}
The catch: held requests live in the page’s memory. Close the tab before signal comes back and they’re gone. A durable queue (IndexedDB plus Background Sync) is the obvious next step if that turns out to bite people in practice.
Trusting the phone’s clock, but not too far
Holding requests creates a new bug. Someone taps Stop on a timer in a basement at 16:00, signal comes back at 16:20, and the server cheerfully records 16:20. Twenty minutes of overtime nobody did.
So every start and stop action sends the time of the tap, and the server decides whether to believe it. The rules: a missing, unreadable or future time (phone clock running fast) becomes now; anything over 7 days old is refused.
const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000
export function tappedAt(at: unknown, now: Date = new Date()): Date {
if (typeof at !== 'string' || at.length > 40) return now
const time = Date.parse(at)
if (!Number.isFinite(time) || time > now.getTime()) return now
if (now.getTime() - time > MAX_AGE_MS) {
throw new Error('That time is too long ago.')
}
return new Date(time)
}
The same rule exists in Postgres, because some writes are multi-step SQL functions that have to be all-or-nothing:
create or replace function tapped_at(p_at timestamptz)
returns timestamptz language plpgsql stable as $$
declare
v_now timestamptz := statement_timestamp();
begin
if p_at is null or p_at > v_now then
return v_now;
end if;
if p_at < v_now - interval '7 days' then
raise exception 'That time is too long ago.';
end if;
return p_at;
end;
$$;
On top of that, an end is never allowed before its start, so a phone clock running slow can’t produce negative hours. Having the rule twice sounds like a maintenance trap, and it would be, except there are tests that read the SQL and check both copies still agree.
Money is integer pence, full stop
Floats and money don’t mix: 0.1 + 0.2 is not 0.3, and an invoice that’s a penny out is the kind of thing a customer notices. Every amount in Kev is an integer number of pence, and pounds only exist at the edges, when someone types a figure or reads one.
Parsing is done as text, so a float never gets a look in:
const POUNDS_PATTERN = /^\d{1,9}(\.\d{1,2})?$/
export function parsePoundsToPence(input: string): number | null {
const cleaned = input.replace(/[£,\s]/g, '')
if (!POUNDS_PATTERN.test(cleaned)) return null
const [whole, fraction = ''] = cleaned.split('.')
const pence = Number(whole) * 100 + Number(fraction.padEnd(2, '0'))
return Number.isSafeInteger(pence) ? pence : null
}
"£1,234.5" comes out as 123450, and "12.345" is rejected rather than rounded. VAT rates get the same treatment as basis points, so 20% is 2000.
Receipts rarely give you all three of net, VAT and total, so one small function fills in whichever is missing from the other two:
export function completeAmounts({ netPence, vatPence, totalPence }: Amounts): Amounts {
if (totalPence === null && netPence !== null && vatPence !== null)
return { netPence, vatPence, totalPence: netPence + vatPence }
if (netPence === null && totalPence !== null && vatPence !== null)
return { netPence: totalPence - vatPence, vatPence, totalPence }
if (vatPence === null && totalPence !== null && netPence !== null)
return { netPence, vatPence: totalPence - netPence, totalPence }
return { netPence, vatPence, totalPence }
}
The UK tax year starts on 6 April
Not 1 January, not 1 April. 6 April, for reasons that go back to the calendar change in 1752. Mileage claims, the 10,000-mile threshold where the HMRC rate drops from 55p to 25p a mile for cars and vans, and the tax summaries all run on it.
export function getUkTaxYear(date: Date): string {
const year = date.getFullYear()
const startYear =
date.getMonth() > 3 || (date.getMonth() === 3 && date.getDate() >= 6)
? year
: year - 1
return `${startYear}-${String(startYear + 1).slice(-2)}`
}
getMonth() is zero-based, so 3 is April, which is exactly the sort of thing that deserves a test for 5 and 6 April specifically. Anything with a monthly allowance counts months in Europe/London rather than UTC, because an expense added at 00:30 on 1 November in Britain is a November expense, whatever the server thinks.
Reading receipts with Claude
Kev Pro can read a receipt photo and fill in the supplier, date, amounts and HMRC category. Three bits make it work well on a phone.
Shrink the photo first
Phone photos are 3 to 5 MB at 4000 px and up. Receipt text is still sharp at 2000 px on the long edge, and the smaller file uploads faster on bad signal and costs less to read. So the browser scales it down before upload:
const bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' })
const scale = Math.min(1, 2000 / Math.max(bitmap.width, bitmap.height))
const canvas = document.createElement('canvas')
canvas.width = Math.round(bitmap.width * scale)
canvas.height = Math.round(bitmap.height * scale)
const ctx = canvas.getContext('2d')!
ctx.fillStyle = '#ffffff' // JPEG has no transparency
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height)
const blob = await new Promise<Blob | null>((r) => canvas.toBlob(r, 'image/jpeg', 0.85))
imageOrientation: 'from-image' applies the camera’s rotation, so the receipt arrives upright. PDFs, images the browser can’t decode, and results that wouldn’t actually be smaller go up unchanged, so this can never block an upload.
Ask for JSON with a schema
The model is Claude Haiku, which reads printed receipts well and costs about a tenth of a penny each. Rather than forcing a tool call, it uses structured outputs, so the reply has to match a JSON schema:
const message = await client.messages.create({
model: EXTRACTION_MODEL,
max_tokens: 4096, // room for thinking as well as the short answer
output_config: {
effort: 'medium',
format: { type: 'json_schema', schema },
},
messages: [{ role: 'user', content: [imageBlock, { type: 'text', text: instructions }] }],
})
Don’t trust the answer either
A reply only counts if the model finished normally. Anything that stopped on max_tokens or a refusal is treated as unread, and what’s left still goes through Zod:
function replyJson(message: Anthropic.Message): unknown {
if (message.stop_reason !== 'end_turn') return undefined
const text = message.content.find((b) => b.type === 'text')
if (!text) return undefined
try { return JSON.parse(text.text) } catch { return undefined }
}
const parsed = invoiceExtractionSchema.safeParse(replyJson(message))
If reading fails for any reason (a timeout, bad JSON, or the monthly allowance used up), the receipt is still saved and marked for the user to fill in by hand. The photo is never lost because the AI had a bad day. The same function also reads CIS payment statements, with a different schema and instructions.
What’s next
The next big job is Making Tax Digital for Income Tax: sending quarterly updates straight to HMRC. That means OAuth, fraud-prevention headers and getting the software recognised by HMRC, so it’ll get its own post.
If you want to poke at the result, Our Kev has a free plan, and the CIS refund calculator and mileage calculator work without an account.