DEV Community

Revercue
Revercue

Posted on

The data model behind a freelancer's client thread

Every freelancer I know runs the same five tools badly: a doc for the proposal, a PDF for the contract, a form for requirements, an invoicing app, and a spreadsheet that is allegedly the CRM. Each one is fine alone. Together they produce the specific frustration of not being able to answer "what did we agree, and what is still unpaid?" without opening five tabs.

The fix is not a better spreadsheet. It is a data model where the client is the centre and the documents hang off it. This post is that model: the tables, the status machines, the money handling, and the parts that are easy to get wrong. It is the schema I wish I had started with.

The four entities (and the two that look like entities but are not)

A client thread needs exactly four things:

  1. Client — the business relationship. The thing you would call "Acme Co".
  2. Person — a human at that client. Might be one, might be four (the approver, the payer, the one who replies).
  3. Document — proposal, contract, requirement form, invoice. Same lifecycle, different payload.
  4. Event — something that happened: opened, section reached, approved, paid, note added.

The two impostors are project and task. They feel essential, and for a solo freelancer they are usually a document with a date on it. Adding them early gives you three places to keep status in sync and no extra clarity. Add them when a client genuinely has parallel workstreams, not before.

CREATE TABLE clients (
  id          TEXT PRIMARY KEY,
  owner_id    TEXT NOT NULL,
  name        TEXT NOT NULL,
  currency    TEXT NOT NULL DEFAULT 'USD',
  archived_at INTEGER,
  created_at  INTEGER NOT NULL
);

CREATE TABLE people (
  id         TEXT PRIMARY KEY,
  client_id  TEXT NOT NULL REFERENCES clients(id),
  name       TEXT NOT NULL,
  email      TEXT,
  role       TEXT,           -- approver | billing | day-to-day
  created_at INTEGER NOT NULL
);
Enter fullscreen mode Exit fullscreen mode

The role column is doing more work than it looks. Most "difficult client" stories are really "we never established who approves". Storing it explicitly means the invoice goes to billing and the approval request goes to the approver, and you stop guessing from an email thread.

One documents table, or five?

This is the first real decision, and both answers are defensible.

Five tables (proposals, contracts, forms, invoices) give you tight types and simple queries per kind. The cost is that every cross-kind feature — a client timeline, a dashboard count, a "recent activity" list — becomes a UNION ALL that grows with every new document type.

One table plus a typed payload keeps the cross-kind features trivial and the schema small. The cost is that kind-specific fields either live in JSON or get promoted to columns.

The hybrid that has held up for me:

CREATE TABLE documents (
  id            TEXT PRIMARY KEY,
  owner_id      TEXT NOT NULL,
  client_id     TEXT NOT NULL REFERENCES clients(id),
  kind          TEXT NOT NULL,              -- proposal | contract | form | invoice
  title         TEXT NOT NULL,
  status        TEXT NOT NULL,              -- per-kind machine, see below
  slug          TEXT UNIQUE,                -- public capability URL
  payload       TEXT NOT NULL,              -- JSON, validated at the app layer
  -- promoted columns: the handful you filter, sort or sum on
  amount_minor  INTEGER,
  currency      TEXT,
  due_at        INTEGER,
  source_id     TEXT REFERENCES documents(id),  -- the proposal a contract came from
  accepted_at   INTEGER,
  expires_at    INTEGER,
  created_at    INTEGER NOT NULL,
  updated_at    INTEGER NOT NULL
);

CREATE INDEX documents_client ON documents (client_id, created_at DESC);
CREATE INDEX documents_owner_status ON documents (owner_id, status);
Enter fullscreen mode Exit fullscreen mode

JSON for the body, columns for anything a query touches. The rule I use: if a field appears in a WHERE, ORDER BY, or a dashboard number, it gets a column. Everything else can stay in the payload. Adding a new block type to a proposal should never require a migration.

Status is per kind, not global

A single status enum across all documents is the mistake that forces five boolean columns later. Proposals and invoices move through completely different states:

proposal: draft → sent → viewed → selected → accepted | declined | expired
contract: draft → sent → approved | declined | questions → signed
form:     draft → sent → partial → submitted
invoice:  draft → sent → viewed → paid | overdue | void
Enter fullscreen mode Exit fullscreen mode

Keep one status column, but validate it against a per-kind allowlist. Then write the transition rules down in code as a map, not as scattered if statements:

const TRANSITIONS = {
  proposal: {
    draft: ['sent'],
    sent: ['viewed', 'selected', 'declined', 'expired'],
    viewed: ['selected', 'declined', 'expired'],
    selected: ['accepted', 'declined'],
    accepted: [], declined: [], expired: ['sent'],
  },
} as const;
Enter fullscreen mode Exit fullscreen mode

Two rules that save arguments later: a declined document is not deleted (declines are the most useful history you have), and accepted is terminal for the content. If the client accepted a proposal, the proposal's text must stop changing — which leads to the next section.

Snapshots, because accepted means frozen

The moment a proposal is accepted, it becomes evidence. If the user can still edit it afterwards, every later dispute is unresolvable: you cannot prove what was agreed.

The cheap version is a version table:

CREATE TABLE document_versions (
  id          INTEGER PRIMARY KEY AUTOINCREMENT,
  document_id TEXT NOT NULL REFERENCES documents(id),
  payload     TEXT NOT NULL,
  created_at  INTEGER NOT NULL,
  created_by  TEXT NOT NULL
);
Enter fullscreen mode Exit fullscreen mode

On accept, write a version and set accepted_version_id. The contract's payload then references the accepted proposal version, not "the proposal". When someone asks in month four why the price is what it is, the answer is a row, not a memory.

Snapshots also give you a safe way to allow editing after sending: edit freely, because the client is looking at the last published version, not your live draft. That is the difference between a document editor and a document you sent.

Money in integers, one currency per document

Two rules and a small table:

  • Store amounts in minor units (amount_minor, integer cents/pence). Floating point money is a bug that shows up in month three.
  • Currency lives on the document, not on the client, because a client can be billed in two currencies and each document must be internally consistent.
CREATE TABLE invoice_lines (
  id             INTEGER PRIMARY KEY AUTOINCREMENT,
  document_id    TEXT NOT NULL REFERENCES documents(id),
  description    TEXT NOT NULL,
  quantity       INTEGER NOT NULL DEFAULT 1,   -- thousandths if fractional
  unit_minor     INTEGER NOT NULL,
  tax_rate_bp    INTEGER NOT NULL DEFAULT 0,   -- basis points, 2000 = 20%
  position       INTEGER NOT NULL
);
Enter fullscreen mode Exit fullscreen mode

Tax as basis points avoids the classic 0.2 * 100 rounding drift, and it keeps the calculation auditable. Round once, at the line-total boundary, with an explicit policy (round half up, or bankers rounding — pick one and write it in a comment, because the difference will appear in an invoice one day).

Payment, importantly, is not card processing. An invoice can record "paid" with a reference and a proof-of-payment upload from the client. That keeps you out of PCI scope entirely and works for bank transfers, which is how most freelance invoices are actually settled.

Events as the spine of the record

A CRM built on a last_contacted column is dead within a month. The record should be derived from events instead:

CREATE TABLE events (
  id          INTEGER PRIMARY KEY AUTOINCREMENT,
  owner_id    TEXT NOT NULL,
  client_id   TEXT REFERENCES clients(id),
  document_id TEXT REFERENCES documents(id),
  kind        TEXT NOT NULL,           -- opened | section | note | sent | paid | call
  body        TEXT,                    -- note text, not log spam
  created_at  INTEGER NOT NULL
);
Enter fullscreen mode Exit fullscreen mode

With that, the client timeline is one query, and every number on the dashboard is a COUNT or a SUM rather than a field someone has to remember to update:

-- The client record, in the order it happened
SELECT kind, created_at,
       COALESCE(body, (SELECT title FROM documents d WHERE d.id = events.document_id)) AS label
FROM events
WHERE client_id = ?1
ORDER BY created_at DESC
LIMIT 50;
Enter fullscreen mode Exit fullscreen mode
-- Money that is still owed
SELECT c.name, SUM(d.amount_minor) AS owed_minor, d.currency
FROM documents d JOIN clients c ON c.id = d.client_id
WHERE d.kind = 'invoice' AND d.status IN ('sent', 'viewed', 'overdue')
GROUP BY d.client_id, d.currency;
Enter fullscreen mode Exit fullscreen mode

Notice what is missing: no interest_score column, no last_activity denormalisation. Both are derived. An interest indicator computed as arithmetic over events (opens, sections, decisions, recency) can change its formula next month without a migration, and nobody has to trust a stale field.

Tenancy in every query, not after it

If the app has accounts, every row needs an owner and every query needs a filter. The failure mode is subtle and common: you fetch a document by id, then check ownership in application code, and one forgotten if exposes a client's contract.

Bake it into the query:

const doc = await db.prepare(
  'SELECT * FROM documents WHERE id = ?1 AND owner_id = ?2'
).bind(id, session.userId).first();
Enter fullscreen mode Exit fullscreen mode

And on the public side, look up by slug only — never by id — with status, expires_at and revoked_at checked in the same statement. Two different access paths, two different queries, no shared "find by id" helper that can be pointed at the wrong caller.

Retention, deletion, and the part nobody models

The bit every schema blog skips: what happens when a plan downgrades or a document ages out.

  • Archive is a state, not a delete. archived_at keeps the row queryable for retention and removes it from the active count.
  • Expiry is checked at read time. expires_at in the public route means an expired link shows a clear page even if the cleanup job has not run yet.
  • Deletion cascades documents and events, but not the client. The client row is the relationship; the documents were rented. Keep the relationship and the notes that describe it.
  • An export exists before any deletion. The PDF or JSON goes out first, with a date. "Your data is yours" is a schema feature, not a marketing line.

Order matters inside the cascade: snapshot, notify, wait, delete. Deleting first and emailing later is how a product earns a support ticket it cannot resolve.

The fixture that tests the whole thing

A schema is only as good as the ugliest realistic case it can hold. I keep one seed that builds a two-month project end to end:

  • A client with two people: an approver and a billing contact.
  • A proposal with three packages, one selected, then accepted.
  • A contract generated from the accepted proposal version, approved, then questioned about a clause, then approved again.
  • A requirements form submitted partially, then completed after a reminder.
  • A deposit invoice paid with a proof upload, and a final invoice overdue by nine days.
  • A change request that added 6 hours and moved the total by 480 in minor units.

If a query on the dashboard, the client timeline, or the invoice list breaks on that seed, something in the model is wrong. If it holds, you have a product, not a set of tables.

The honest limits

  • An approval record is not a qualified electronic signature. If a contract needs legal e-signature in your jurisdiction, this model records consent but does not replace an e-signature provider. Say that in the UI.
  • No card processing. Recording a payment is not charging one. Keeping that boundary is a feature, not a gap.
  • A JSON payload is not free. You lose database-level constraints on body fields; validate on write, and version the payload shape so old documents keep rendering after a block type changes.
  • One workspace per user is a simplification. The moment a second person needs access, you need roles and an audit log, and that is a different post.

What to take away

  • The client is the centre; documents hang off it; events are the spine.
  • One documents table with a typed payload and a few promoted columns gets you both flexibility and query speed.
  • Status machines are per kind, terminal states are real, and accepted content gets snapshotted.
  • Money in integers, currency on the document, tax in basis points.
  • Derive the numbers, filter by owner in the same query, and design deletion before you need it.

A thread is not a feature you add later. It is a schema decision you make on day one, and it is the difference between five apps and one record.


I build Revercue, which keeps proposals, contracts, requirement forms, invoices and the client record on one thread, with a free plan that covers five active documents. If you have modelled this differently — especially the version/snapshot part — I would like to hear what broke for you.

Top comments (0)