Service-business operations · Alpha · Public source

SVC: the workflow between an agreement and a paid invoice

Software for the workflow between an agreement and a paid invoice: clients, projects, time, billing, and a permissioned client portal. The engineering focus is making business state explicit and holding automation to the same rules as the application.

A small consultancy runs on a chain of commitments. A client signs an agreement: say, a monthly retainer of 20 hours, unused hours roll over for three months, and anything beyond that is billed at the hourly rate. People do the work and log time. Someone decides which of that time is billable. At the end of the month, an invoice turns all of it into a number that a client is asked to pay.

Every link in that chain is simple on its own. The hard part is keeping them consistent: the same hour must not be sold twice, work must not go unbilled because it fell between two periods, and a client must never see a description written for the team.

SVC is an open-source, self-hosted application for that chain. It is alpha software. When this was written, in September 2026, it was about six weeks old, with 227 merged pull requests and roughly 1,700 backend tests. This post covers who it is for, how it compares, how it works, and the problems that turned out to be hard.

Who uses it, and what they need

There are four kinds of user, and they need different things from the same records.

The business owner sets up clients, agreements, and billing schedules, then reviews, issues, and sends invoices. They need to trust that an invoice is right without re-deriving it by hand: which hours drew on the retainer, which rolled over, which were overage.

Staff log time against projects and tasks. Contributors manage their own draft time. Project managers approve it. Approval is the point where time becomes billable, so it snapshots the rate from the agreement in force.

The client signs in to a portal. They see their agreements, invoices, and the approved work their provider chose to share, written in a client-facing description. They can download PDFs and pay an issued invoice online.

An AI agent connects over the Model Context Protocol (MCP) with OAuth. The everyday case is logging time from whatever repository the work happened in: "log 90 minutes to the SVC project for the webhook fix." With extra permissions, an agent can draft invoices or record a payment that has already been received.

Compared with ActiveCollab and Basecamp

ActiveCollab is the closest match in scope, and still ships a self-hosted edition. Basecamp covers collaboration: it has timesheets, but no rates, retainers, or invoices. Both are far more mature, with mobile apps, integrations, and agent access of their own.

Client visibility Retainer rollover and overage Issued invoices Hosting
ActiveCollab Visible unless hidden; time and expenses by one workspace switch Budgets reset with alerts; overage left to you Editable SaaS or self-hosted, proprietary
Basecamp Hidden until shared No billing No invoices SaaS
SVC Hidden until shared, including time and billing Rollover and overage billed from the same ledger Immutable except a narrow, audited correction Self-hosted, open source

Design goals

1. An issued invoice is a record, not a document. Once issued, an invoice is final: it has claimed specific approved time, drawn on specific retainer capacity, and taken a number from a gapless sequence. SVC has a void, which releases the time, and a narrow correction path for invoices that are unpaid and never delivered to a client. The correction requires the expected revision and a reason.

2. Retainer arithmetic lives next to the invoice. Rollover, catch-up minimums, and overage are computed from the same ledger that produces the invoice lines. Tracking hours in one place and billing them somewhere else is how double billing happens.

3. Hidden until shared, for billing too. A time entry reaches the portal only when it is marked client-visible and approved and has a client-facing description. An earlier version filtered on visibility alone, and showed clients work that nobody had approved yet, including work that was later rejected.

4. Automation gets narrower rights than people. Each class of consequence has its own switch, not just the user's role.

5. State describes what is known. "Sent" means an email left SVC, not that it arrived. "Payment recorded" means money was received somewhere else, not that SVC moved it.

How it works

SVC is a Laravel application with a React front end, deployed to ordinary shared hosting.

State machines instead of flags

Every billable object has an explicit lifecycle:

time entry   draft ⇄ approved → invoiced        (voiding the invoice: invoiced → approved)
invoice      draft → issued → partially_paid → paid
                            ↘ void
payment      pending → succeeded | failed | refunded | disputed | canceled

Issuing is the commitment point. In one transaction, it locks the invoice, moves its linked time from approved to invoiced, spends any overpayment credit, and takes the next invoice number. The administrator notification is registered inside the transaction and sent after it commits, so a rolled-back issue cannot announce itself.

Money is integers

Amounts are integer minor units plus an ISO 4217 currency code. Durations are integer minutes. Hourly amounts round half-up in integer arithmetic (minutes × rate / 60), and quantity-times-price uses rational arithmetic with overflow guards. Decimal hours exist only on screen.

Tenancy in four layers

Each business row belongs to a workspace, and isolation is enforced four times over:

  • Routing. Route binding resolves the workspace, checks membership, and then reads the child record under that workspace in SQL. Anything inaccessible is a 404, not a 403, so the response does not confirm that a record exists.
  • Schema. Composite foreign keys, (workspace_id, parent_id) → parent(workspace_id, id), make a cross-tenant reference impossible to store. An audit command counts the exemptions and states the reason for each.
  • Writes. Eloquent keys a save() by primary key alone, so a model read through a perfectly scoped query still writes where id = ?. A trait adds workspace_id to every save, delete, restore, and increment.
  • No ambient tenant. Nothing depends on a mutable "current workspace." Tenancy is explicit in each query and policy.

Agents: versions, receipts, and gates

The agent API, and the MCP server on top of it, follows three rules.

Every mutation names the version it read. Records carry an opaque version: an HMAC of type, ID, and a lock counter. Writes that supply a stale version are refused rather than merged.

Every mutation carries an idempotency key. The key is reserved before any work happens, as a receipt scoped to workspace, OAuth client, user, and operation, over a canonical digest of the request. An identical retry returns the original result. The same key with a different body returns a 409. The receipt, the business write, and its audit entry commit together.

Capabilities follow consequences. An outer switch, off by default, enables agent writes at all. Invoices, payments, expenses, and clients each need their own switch as well, and each is also off by default. Token scopes then narrow discovery further, so an agent without billing:write never sees the invoice tools. Recording a payment that was already received is possible. Initiating a charge, a refund, or anything involving card data is not exposed to agents at all.

The reason is blast radius. Logging time is recoverable. Issuing an invoice allocates approved time irreversibly, and sending one puts a document in front of a paying client.

The hard problems

1. Porting a billing engine without silently moving money

SVC's retainer engine was ported from an earlier system: draw-down, rollover, catch-up billing, prior-period cycles, and interim overage. The question was never "does it run?" It was "does it bill every historical month exactly as it should have, and where it differs, is the difference a deliberate correction?"

The answer is a replay command. It regenerates history inside a transaction that always rolls back, compares every line with what was actually billed, and classifies each divergence. Only five narrowly proven rules can waive one.

The first runs were mostly measuring the harness, not the engine:

  • The harness manufactured findings. It blanked invoices for regeneration but left their payment rows behind, so the credit ledger read every settled invoice as overpaid by its full amount. Eight "divergences" were its own.
  • The classifier waived what it most needed to report. Whole-invoice disappearances were explained away because the agreement had rollover enabled, but no capacity correction can move a contracted fee.
  • The import was reading deleted rows. Most of the imported invoices, and nearly all of their lines, had been soft-deleted in the source and arrived as live data. That one bug had been blamed on "inconsistent historical data," which the project's own documentation now calls "the one conclusion that stops you looking."

After the three fixes, exact reproduction went from 4 of 42 invoices to 19 of 24. The remaining differences are named individually.

The lesson generalised into a rule: a check must distinguish "passed" from "did not run," and fail when it cannot. A rehearsal command once reported generation as safe when every period had thrown, because the generator returned exceptions as skips.

2. Billing the same month twice, or never

Two bugs, found together:

  • A correction invoice for 1–15 February derived the same retainer cycle as January's invoice. Their service periods did not overlap, so the overlap guard let February's retainer be sold twice.
  • Work claimed by a draft interim invoice was invisible to the monthly invoice, so it could go unbilled.

A third was quieter. The line types excluded from an invoice's service period were a denylist naming retainer and credit. Recurring items, dated a month ahead by design, therefore pushed the period forward. The overlap guard then refused that month permanently and swallowed the refusal, so a client silently stopped being invoiced.

The fix was an allowlist of the line types that define the work period. The general rule: wherever a missing entry means something is billed, skipped, or hidden, use an allowlist. A missing allowlist entry makes a period visibly too narrow. A missing denylist entry stopped billing silently.

3. NULL in billing math

SQL's null semantics are a quiet source of money bugs. A null service_period_end makes every date comparison false. A SUM over nulls contributes zero. Together, charged overage could vanish from the ledger and be sold again. A PHP detail made it worse: Carbon::parse(null) returns now, so a termination charge was dated to whenever the termination job happened to run.

Fixing these one at a time would never finish, so a registry test enumerates all 72 nullable columns on the four billing tables. Each one's null behaviour must be pinned by a test or explicitly declared, and a new nullable column fails the suite until someone decides what null means for it. Alongside it, readers of ambiguous state fail closed. An unrecognised invoice status is treated as settled and untouchable, not as a draft, because draft is the least privileged state to read but the most permissive to write.

4. Fifty-one locks, one order

Billing takes row locks in 51 places. Any two code paths that take the same locks in different orders can deadlock under load, and no single review sees both paths.

SVC has one lock-order registry: 22 tables in a fixed order, taken only through a helper. A PHPStan rule rejects a raw lockForUpdate() anywhere else, and a conformance test records the locks real transactions take and fails on any backwards step.

The registry surfaced one surprise: the client company is locked last, not first, because it serialises spending from the shared overpayment-credit pool. It also found a real inversion. Interim overage took time entries before the invoice-number counter. The fix locks the numbering row early without drawing a number, so the sequence stays gapless. The same review recorded that the two invoice generators locked different rows, the schedule and the agreement, so both could bill the same month. They now serialise on the agreement. One inversion remains, inside the rollback-only replay command, and it is not run while a workspace is generating invoices.

5. Tenancy as a property, not a habit

A review found that saving an expense could, in principle, write across workspaces, because of the primary-key-only save() described above. The tempting fix was the expense model. The pull request that closed it said the finding was not about that model: "ClientExpense was not the model with the problem, it was the model that got reviewed." The same behaviour existed on all 28 tenant-owned models, so the fix went into a shared trait with a test that enumerates every model.

This became the project's most consistent habit. When findings keep landing on one unnamed property at several sites, name the property, fix it once, and test the list of sites.

6. Events arrive out of order

Payment and email providers send webhooks late, twice, and out of order.

  • Payments. Stripe events older than the last one applied are ignored. Within a tied timestamp, failed is never replaced by pending. A permutation test replays every ordering of a payment's event sequence (up to 720 of them), plus duplicate deliveries, and checks that the database ends in the same state every time. Refused deliveries must leave every table byte-for-byte unchanged.
  • Email. Delivery status is ranked by severity, compared and written under a row lock, rather than last-write-wins: delivered or opened ranks below deferred, which ranks below bounced. A code comment gives the reason: "an invoice that bounced and was then marked 'opened' by a scanner did not arrive." SVC's own status, meaning "left here," is stored separately from the provider's.

7. The test database lied

Tests ran on SQLite, production runs MariaDB, and SQLite let through three real bugs: an h:mm string written into a decimal column, a negative number written into an unsigned column, and a date comparison that was wrong in reverse. A MariaDB CI lane now gates deployment. A related gap: invoice delivery was queued in production with no worker running, while tests passed because PHPUnit runs queued jobs inline. Delivery is now synchronous, and a test fails if anything queues work.

A pattern: fix the shape, not the site

Five review passes over the billing port found 62 defects that its tests had missed. Almost all of them fell into five shapes:

  1. A rule restated in several places and wrong in one.
  2. An exhaustive list that went stale.
  3. A default chosen where the concept did not apply.
  4. A check that measured its own interference.
  5. A check that reported success for a case it never examined.

Each shape now has something structural holding it shut: one definition plus a guard test that fails if the rule is written out again, allowlists, restrictive defaults, and checks that distinguish "passed" from "did not run."

What it does not do

SVC is deliberately narrow. Banking, tax calculation, payroll, and accounting stay in external systems. Tax is a per-line amount supplied by the caller, and a finance API lets an external system reconcile payments rather than SVC pretending to be a ledger. Online card payment is capped by default. There is no mobile app and no accounting sync.

It is also alpha, and its documentation says where. Interim overage invoices are implemented but have not yet run for a real client. Five replay divergences are still unexplained.

Technical details are as of commit adf200a. The billing rules and their failure history are in the client-management reference. Product comparisons reflect vendor documentation in September 2026.